package com.uzai.console.service.wechatprivate.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.device.DeviceInfoBaseCache;
import com.uzai.common.dto.device.DeviceInfoMobileWeChatCacheDto;
import com.uzai.common.dto.device.DeviceInfoPcWeChatCacheDto;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.Math;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Mobiletype;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.constant.Const;
import com.uzai.console.dto.alipaydetail.AlipayDetailCreateDto;
import com.uzai.console.dto.device.deviceauth.DeviceAuthQuery;
import com.uzai.console.dto.module.deviceproduct.DeviceProductQuery;
import com.uzai.console.dto.rocketmq.androidapp.UpdateAndroidAppDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.CloseClientAppDto;
import com.uzai.console.dto.rocketmq.devicewechatinfo.UpdateClientAppDto;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.*;
import com.uzai.console.entity.*;
import com.uzai.console.enums.*;
import com.uzai.console.jsonvo.merbaseconfig.RealNameVerificationJson;
import com.uzai.console.mapper.*;
import com.uzai.console.service.alipaydetail.AlipayDetailService;
import com.uzai.console.service.deviceauth.DeviceAuthService;
import com.uzai.console.service.feign.ClientApiService;
import com.uzai.console.service.feign.UzaiImClientFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoCardPayService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoService;
import com.uzai.console.service.wechatprivate.DeviceWechatInfoSyncService;
import com.uzai.console.service.wechatprivate.WxContactsService;
import com.uzai.console.vo.alarm.alarmrule.AlarmRuleInfoVo;
import com.uzai.console.vo.alipaydetail.businessinfo.DeviceAddBusinessInfo;
import com.uzai.console.vo.alipaydetail.businessinfo.DeviceAuthBusinessInfo;
import com.uzai.console.vo.deviceauth.DeviceAuthVo;
import com.uzai.console.vo.deviceproduct.DeviceProductVo;
import com.uzai.console.vo.wechatprivate.devicewechatinfo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 机器人
 *
 * @author liuqi
 * @date 2021年08月19日 16:50
 */
@Service
public class DeviceWechatInfoServiceImpl implements DeviceWechatInfoService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private DeviceGroupMapper deviceGroupMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private JdTokenMapper jdTokenMapper;
    @Autowired
    private PddTokenMapper pddTokenMapper;
    @Autowired
    private VphTokenMapper vphTokenMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private DeviceVersionMapper deviceVersionMapper;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private DeviceAuthMapper deviceAuthMapper;
    @Autowired
    private DeviceAuthDetailMapper deviceAuthDetailMapper;
    @Autowired
    private DevicePriceMapper devicePriceMapper;
    @Autowired
    private AlipayDetailService alipayDetailService;
    @Autowired
    private AlipayDetailMapper alipayDetailMapper;
    @Autowired
    private CdkeysMapper cdkeysMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;
    @Autowired
    private DeviceWechatInfoSyncService deviceWechatInfoSyncService;
    @Autowired
    private DeviceProductMapper deviceProductMapper;
    @Autowired
    private DeviceWechatInfoCardPayService deviceWechatInfoCardPayService;
    @Autowired
    private AlarmRuleMapper alarmRuleMapper;
    @Autowired
    private CdkeysMobileAppMapper cdkeysMobileAppMapper;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private TbOrderMapper tbOrderMapper;
    @Autowired
    private JdOrderMapper jdOrderMapper;
    @Autowired
    private PddOrderMapper pddOrderMapper;
    @Autowired
    private VphOrderMapper vphOrderMapper;
    @Autowired
    private MtOrderMapper mtOrderMapper;
    @Autowired
    private DyOrderMapper dyOrderMapper;
    @Autowired
    private DeviceAuthService deviceAuthService;
    @Autowired
    private UzaiImClientFeignService uzaiImClientFeignService;
    @Autowired
    private WxContactsService wxContactsService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private ClientApiService clientApiService;

    /**
     * 查询个人微信机器人列表
     *
     * @param deviceWechatInfoQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Page<DeviceWechatInfoVo> findDeviceWechatInfoList(DeviceWechatInfoQuery deviceWechatInfoQuery) {

        //手动处理机器人分页查询-如果是机器人昵称，则按照中文gbk排序
        List<OrderItem> orderItemList = deviceWechatInfoQuery.getOrderItemList();
        if (orderItemList != null && orderItemList.size() > 0) {
            for (OrderItem orderItem : orderItemList) {
                if ("deviceName".equals(orderItem.getColumn())) {
                    orderItem.setColumn(" convert( " + orderItem.getColumn() + " using gbk) ");
                } else if ("deviceRemark".equals(orderItem.getColumn())) {
                    orderItem.setColumn(" convert( " + orderItem.getColumn() + " using gbk) ");
                }
            }
        }

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<DeviceWechatInfoVo> deviceWechatInfoPageVoList = new ArrayList<>();
        //执行分页查询对象
        Page<DeviceWechatInfo> page = new Page<>();
        deviceWechatInfoQuery.convert(page);

        ArrayList<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findListByAuthGroup(page, deviceWechatInfoQuery);
        if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {
            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {

                DeviceWechatInfoVo deviceWechatInfoPageVo = new DeviceWechatInfoVo();
                BeanUtils.copyProperties(deviceWechatInfo, deviceWechatInfoPageVo);

                //判断接收消息
                if (deviceWechatInfo.getRecvmsgType() != null) {
                    //移动端接收消息
                    if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()) {
                        deviceWechatInfoPageVo.setPcMsgHandler(0);
                        deviceWechatInfoPageVo.setMobileMsgHandler(1);
                        //电脑端接收消息
                    } else if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId().intValue()) {
                        deviceWechatInfoPageVo.setPcMsgHandler(1);
                        deviceWechatInfoPageVo.setMobileMsgHandler(0);
                    }
                }

                //机器人分组
                DeviceGroup deviceGroup = deviceGroupMapper.selectById(deviceWechatInfo.getGroupId(), deviceWechatInfo.getMerId());
                if (deviceGroup != null) {
                    deviceWechatInfoPageVo.setGroupName(deviceGroup.getName());
                }
                //获取配置方案信息
                ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
                if (configPlan != null) {
                    deviceWechatInfoPageVo.setConfigName(configPlan.getName());
                }

                //是否可以转移授权时间
                boolean transferAuthTimeFlag = false; //默认不可以

                //授权信息
                List<DeviceAuthVo> deviceAuthVoList = new ArrayList<>();
                DeviceAuthQuery deviceAuthQuer = new DeviceAuthQuery();
                deviceAuthQuer.setDeviceId(deviceWechatInfo.getDeviceId());
                //deviceAuthQuer.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuer);
                if (deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //名片转移功能暂时不显示-过期了
                        if (!DeviceProductEnum.BANTRANSFER.getValue().equals(deviceAuth.getProductCode())) {
                            DeviceAuthVo deviceAuthVo = new DeviceAuthVo();
                            BeanUtils.copyProperties(deviceAuth, deviceAuthVo);
                            DeviceProductKeyEnum deviceProductKeyEnum = DeviceProductKeyEnum.getValue(deviceAuth.getProductCode());
                            if (deviceProductKeyEnum != null) {
                                deviceAuthVo.setProductName(deviceProductKeyEnum.getDesc());
                            }
                            //到期时间
                            Integer expiretime = Tools.getInteger(deviceAuthVo.getExpireTime());
                            if (expiretime.intValue() <= now.intValue()) {
                                deviceAuthVo.setExpireStatus(0);  //已到期
                            } else if (expiretime.intValue() > now && expiretime.intValue() <= now + 7 * 24 * 3600) {
                                deviceAuthVo.setExpireStatus(2);  //即将到期
                            } else {
                                deviceAuthVo.setExpireStatus(1);  //未到期
                                transferAuthTimeFlag = true; //只要有未到期的授权产品，就可以转移授权时间
                            }
                            deviceAuthVoList.add(deviceAuthVo);
                        }
                    }
                }

                //封装PC端授权记录
                deviceWechatInfoPageVo.setDeviceAuthVoList(deviceAuthVoList);

                //设置是否可以转移授权时间
                if (transferAuthTimeFlag) {
                    deviceWechatInfoPageVo.setTransferAuthTimeFlag(1);
                } else {
                    deviceWechatInfoPageVo.setTransferAuthTimeFlag(0);
                }

                //从缓存中换取个人微信PC端信息
                deviceWechatInfoPageVo.setPcDeviceAuthStatus(0);//未授权
                Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                if (object_pc != null) {
                    DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);
                    //PC端个人微信信息不为空
                    if (deviceInfoPcWeChatCacheDto != null) {
                        //有pc端授权
                        deviceWechatInfoPageVo.setPcDeviceAuthStatus(1);//有授权
                        //封装pc端授权
                        deviceWechatInfoPageVo.setPcDeviceAuthVoList(deviceAuthVoList);

                        //客户端版本号
                        deviceWechatInfoPageVo.setPcClientVersion(deviceInfoPcWeChatCacheDto.getClientVersion());
                        deviceWechatInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.NO_UPDATE.getId()); //默认版本相同，不更新
                        //查询机器人最新版本
                        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                        if (deviceVersion != null) {
                            if (deviceVersion.getVersion() != null) {
                                //版本号不相等，有更新
                                if (!deviceVersion.getVersion().equals(deviceInfoPcWeChatCacheDto.getClientVersion())) {
                                    deviceWechatInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.HAVE_UPDATE.getId()); //版本号不相同，需要更新
                                    Integer updateClientVersionStatus = deviceInfoPcWeChatCacheDto.getUpdateClientVersionStatus();
                                    Integer updateClientVersionTime = deviceInfoPcWeChatCacheDto.getUpdateClientVersionTime();
                                    if (updateClientVersionStatus != null && updateClientVersionStatus == DeviceUpdateVersionStatusEnum.UPDATING.getId().intValue()) {//更新中
                                        deviceWechatInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.UPDATING.getId());
                                        if (DateUtil.getNowTime() - updateClientVersionTime > Const.Device.UPDATE_VERSION_VALIDITY_TIME) {//更新失败
                                            deviceWechatInfoPageVo.setUpdatePcClientVersion(DeviceUpdateVersionStatusEnum.UPDATE_FAILE.getId());
                                        }
                                    }
                                }
                            }
                        }

                        //PC端微信版本号
                        deviceWechatInfoPageVo.setPcWxVersion(deviceInfoPcWeChatCacheDto.getWxVersion());
                        //是否在线，默认为离线
                        deviceWechatInfoPageVo.setPcOnLine(0);
                        //获取最新心跳时间
                        Integer lastHeartBeatTime = deviceInfoPcWeChatCacheDto.getLastHeartBeatTime();
                        if (lastHeartBeatTime != null) {
                            //判断在线（少于5分钟表示在线）
                            if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                deviceWechatInfoPageVo.setPcOnLine(1); //在线
                            }
                        }

                        //是否处理消息
                        //deviceWechatInfoPageVo.setPcMsgHandler(deviceInfoPcWeChatCacheDto.getMsgHandler());
                        //操作系统版本
                        deviceWechatInfoPageVo.setSysVersion(Tools.getStr(deviceInfoPcWeChatCacheDto.getSysVersion()));
                        //CPU使用率
                        deviceWechatInfoPageVo.setSysCpuUse(Tools.getInteger(deviceInfoPcWeChatCacheDto.getSysCpuUse()));
                        //内存使用率
                        deviceWechatInfoPageVo.setSysMemUse(Tools.getInteger(deviceInfoPcWeChatCacheDto.getSysMemUse()));
                        //磁盘总空间(MB)
                        deviceWechatInfoPageVo.setDiskTotal(Tools.getDouble(deviceInfoPcWeChatCacheDto.getDiskTotal()));
                        //硬盘可使用的空间(MB)
                        deviceWechatInfoPageVo.setDiskFree(Tools.getDouble(deviceInfoPcWeChatCacheDto.getDiskFree()));
                        //客户端CPU和内存使用率JSON
                        String clientJSON = null;//deviceInfoPcWeChatCacheDto.getClient();
                        deviceWechatInfoPageVo.setClient(clientJSON);
                        //客户端CPU使用率
                        if (StringUtils.isNotBlank(clientJSON)) {
                            JSONObject clientJSONObject = JSONObject.parseObject(clientJSON);
                            if (clientJSONObject != null) {
                                deviceWechatInfoPageVo.setClientCpu(clientJSONObject.getDouble("cpu"));
                                deviceWechatInfoPageVo.setClientMemory(clientJSONObject.getDouble("memory"));
                            }
                        }

                        //微信CPU和内存使用率JSON
                        String wechatJSON = null;// deviceInfoPcWeChatCacheDto.getWechat();
                        deviceWechatInfoPageVo.setWechat(wechatJSON);
                        if (StringUtils.isNotBlank(wechatJSON)) {
                            JSONObject wechatJSONObject = JSONObject.parseObject(wechatJSON);
                            if (wechatJSONObject != null) {
                                deviceWechatInfoPageVo.setWechatCpu(wechatJSONObject.getDouble("cpu"));
                                deviceWechatInfoPageVo.setWechatMemory(wechatJSONObject.getDouble("memory"));
                            }
                        }
                    }
                }

                try {
                    //从缓存中获取个人微信手机端信息
                    deviceWechatInfoPageVo.setMobileDeviceAuthStatus(0);//无授权
                    Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                    if (object_mobile != null) {
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);
                        //手机端个人微信信息不为空
                        if (deviceInfoMobileWeChatCacheDto != null) {
                            //手机端封号名片转发信息
                            deviceWechatInfoPageVo.setBanFlag(deviceInfoMobileWeChatCacheDto.getBanFlag());
                            deviceWechatInfoPageVo.setTransferDevcieUniqueId(deviceInfoMobileWeChatCacheDto.getTransferDevcieUniqueId());
                            deviceWechatInfoPageVo.setTransferInfoList(deviceInfoMobileWeChatCacheDto.getTransferInfoList());

                            //有移动端授权
                            deviceWechatInfoPageVo.setMobileDeviceAuthStatus(1);//有授权
                            //封装移动端授权
                            deviceWechatInfoPageVo.setMobileDeviceAuthVoList(deviceAuthVoList);

                            //客户端版本号
                            deviceWechatInfoPageVo.setMobileClientVersion(deviceInfoMobileWeChatCacheDto.getClientVersion());
                            deviceWechatInfoPageVo.setUpdateMobileClientVersion(0); //默认版本相同，不更新
                            //获取机器人最新移动端版本
                            //从缓存中获取版本移动端版本信息
                            Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.MOBILE_APP_UPDATE_INFO.getKey());
                            if (object_mobile_version != null) {
                                JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
                                if (jsonObject != null) {
                                    //软件版本号
                                    Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
                                    //软件版本名称
                                    String version = Tools.getStr(jsonObject.getString("version"));
                                    //包名称
                                    String packageName = Tools.getStr(jsonObject.getString("packageName"));
                                    //软件包URL地址
                                    String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));
                                    //版本号不相等，有更新
                                    if (!version.equals(deviceInfoMobileWeChatCacheDto.getClientVersion())) {
                                        deviceWechatInfoPageVo.setUpdateMobileClientVersion(1); //版本号不相同，需要更新
                                    }
                                }
                            }

                            //移动微信版本号
                            deviceWechatInfoPageVo.setMobileWxVersion(deviceInfoMobileWeChatCacheDto.getWxVersion());
                            //是否在线，默认为离线
                            deviceWechatInfoPageVo.setMobileOnLine(0);
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoMobileWeChatCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWechatInfoPageVo.setMobileOnLine(1); //在线
                                }
                            }

                            //软件到期日期
                            //deviceWechatInfoPageVo.setMobileExpireTime(deviceInfoMobileWeChatCacheDto.getExpireTime());
                            //是否处理消息
                            //deviceWechatInfoPageVo.setMobileMsgHandler(deviceInfoMobileWeChatCacheDto.getMsgHandler());

                            //手机剩余电量百分比
                            deviceWechatInfoPageVo.setBatteryLevel(Tools.getInteger(deviceInfoMobileWeChatCacheDto.getBatteryLevel()));
                            //手机外部存储（sdcard）剩余空间字节数
                            Long sdCardFree = Tools.getLong(deviceInfoMobileWeChatCacheDto.getSdCardFree());
                            deviceWechatInfoPageVo.setSdCardFree(Math.round(sdCardFree / 1024d / 1024d, 2));
                        }
                    }
                } catch (Exception e) {

                }

                //封装报警规则信息
                if (deviceWechatInfo.getAlarmRuleId() != null) {
                    AlarmRule alarmRule = alarmRuleMapper.selectById(deviceWechatInfo.getAlarmRuleId(), deviceWechatInfo.getMerId());
                    if (alarmRule != null) {
                        AlarmRuleInfoVo alarmRuleInfoVo = new AlarmRuleInfoVo();
                        BeanUtils.copyProperties(alarmRule, alarmRuleInfoVo);
                        deviceWechatInfoPageVo.setAlarmRuleInfoVo(alarmRuleInfoVo);
                    }
                }

                //最后登录ip地址
                try {
                    if (StringUtils.isNotBlank(deviceWechatInfo.getLastLoginIp())) {
                        deviceWechatInfoPageVo.setLastLoginIpAddress(Tools.findDeviceIpByRegex(deviceWechatInfo.getLastLoginIp()));
                    }
                } catch (Exception e) {
                    logger.error("解析机器人最后登录ip地址错误，lastLoginIp={}, error={}", deviceWechatInfo.getLastLoginIp(), e.getMessage());
                }

                deviceWechatInfoPageVoList.add(deviceWechatInfoPageVo);

                //刷新授权
                flashDeviceAuth(deviceWechatInfo, deviceAuthList);
            }
        }

        //返回到页面分页对象
        Page<DeviceWechatInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(deviceWechatInfoPageVoList);
        return pageVo;
    }

    /**
     * 查询机器人详情
     *
     * @param deviceWechatInfoIdDto
     * @return DeviceWechatInfoVo
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public DeviceWechatInfoVo findDeviceWechatInfoInfo(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }
        DeviceWechatInfoVo deviceWechatInfoPageVo = new DeviceWechatInfoVo();

        BeanUtils.copyProperties(deviceWechatInfo, deviceWechatInfoPageVo);

        return deviceWechatInfoPageVo;
    }

    /**
     * 添加机器人信息，创建订单
     *
     * @param deviceWechatInfoAddDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public DeviceWechatInfoAddVo addDeviceWechatInfo(DeviceWechatInfoAddDto deviceWechatInfoAddDto) {

        if (true) {//新版添加机器人就只是做添加移动端，如果没有授权则试用5天
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此功能已经不能使用");
        }

        DeviceWechatInfoAddVo deviceWechatInfoAddVo = new DeviceWechatInfoAddVo();
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        Integer now = DateUtil.getNowTime();
        Long merId = deviceWechatInfoAddDto.getMerId();

        //机器人类型id
        Integer deviceTypeId = deviceWechatInfoAddDto.getDeviceTypeId();
        if (deviceTypeId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型id");
        }

        if (deviceTypeId.intValue() != DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持添加机器人移动端");
        }

        //机器人类型key
        String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

        //机器人wxid
        String deviceId = deviceWechatInfoAddDto.getDeviceId();
        if (StringUtils.isBlank(deviceId)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人wxid");
        }

        //授权类型(0试用;1月卡;2年卡)
        Integer authType = deviceWechatInfoAddDto.getAuthType();
        if (authType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
        }

        if (authType.intValue() == DeviceAuthTypeEnum.DAT_FREE.getId().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "购买机器人移动端不支持试用");
        }

        //选择该运营商默认配置方案
        ConfigPlan configPlan = configPlanMapper.selectByIsDefault(deviceWechatInfoAddDto.getMerId(), deviceTypeKey);
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商没有默认的配置方案");
        }

        //查询整个数据库当中正在使用的该微信id
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(deviceId);
        //有在使用的机器人
        if (deviceWechatInfo != null) {
            //该机器人不属于自己运营商，则提示错误
            if (deviceWechatInfo.getMerId().longValue() != deviceWechatInfoAddDto.getMerId().longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信ID已经被其他运营商使用");
            }
        }

        if (deviceWechatInfoAddDto.getPayType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付方式");
        }

        //添加机器人只能购买全包套餐
        DeviceProduct deviceProduct_add = deviceProductMapper.selectByCode(DeviceProductEnum.ALL.getValue());
        if (deviceProduct_add == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置全包套餐");
        }

        //List<String> productCodeList = JSONObject.parseArray(deviceProduct_add.getCodes(), String.class);
        //从枚举中获取关联的产品
        DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_add.getCode());
        List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统全包套餐还没配置包含产品信息");
        }

        //授权数量
        Integer quantity = deviceWechatInfoAddDto.getQuantity();
        if (quantity == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
        }
        //保存到数据库当中的购买月数，按年买需要乘以12月
        Integer quantity_db = 0;
        //新的到期时间
        Integer expired_time = 0;

        //本次授权开始时间默认为现在
        Integer begin_time = now;

        //设备号不为空，则开始时间为数据库中最早的授权时间
        if (StringUtils.isNotBlank(deviceId)) {
            //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
            begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);
        }

        if (deviceWechatInfoAddDto.getAuthType().intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
            //新的到期时间=现在+月数*30天*24小时*3600秒
            expired_time = begin_time + quantity * 30 * 24 * 3600;
            quantity_db = quantity;
        } else {//按年购买
            //新的到期时间=现在+年数*12月*30天*24小时*3600秒
            expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
            quantity_db = quantity * 12;
        }

        //获取总金额
        DeviceAmountDto deviceAmountDto = new DeviceAmountDto();
        BeanUtils.copyProperties(deviceWechatInfoAddDto, deviceAmountDto);
        deviceAmountDto.setOperType(1); //添加机器人
        DeviceAmountVo deviceAmountVo = getAmount(deviceAmountDto);
        //得到本次总金额
        Double amountTotal = Tools.getDouble(deviceAmountVo.getAmountTotal());

        if (amountTotal.doubleValue() <= 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "添加机器人失败");
        }

        if (deviceWechatInfoAddDto.getPayType().intValue() == PaymentTypeEnum.PAY_BALANCE.getId().intValue()) {//余额支付

            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(deviceWechatInfoAddDto.getMerId());
            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }

            //判断余额大小
            Double balance = merchant.getBalance();
            if (balance.doubleValue() < amountTotal.doubleValue()) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance - amountTotal);
            merchant.setUpdateTime(now);
            merchantMapper.updateBalance(merchant);

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(amountTotal);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.DEVICE_MOBILE_ADD.getId());
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //是否新增机器人
            if (deviceWechatInfo == null) {//机器人为空，未还添加，则先添加机器人，默认配置方案
                //添加机器人
                deviceWechatInfo = new DeviceWechatInfo();
                deviceWechatInfo.setId(IdWorker.getId());
                deviceWechatInfo.setMerId(deviceWechatInfoAddDto.getMerId());
                deviceWechatInfo.setDeviceId(deviceWechatInfoAddDto.getDeviceId());
                deviceWechatInfo.setConfigId(configPlan.getId());
                deviceWechatInfo.setRecvmsgType(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());//移动端
                deviceWechatInfo.setDelStatus(DeleteStatusEnum.VALID.getId());//有效
                deviceWechatInfo.setCreateTime(now);
                deviceWechatInfo.setUpdateTime(now);
                //添加机器人
                deviceWechatInfoMapper.insert(deviceWechatInfo);

                //选择该运营商默认配置方案，需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                if (configPlan.getOtherId() != null) {
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWechatInfoAddDto.getMerId());
                    if (sysPlugin != null) {
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWechatInfo.getId()), sysPlugin.getData());
                    }
                }
            }

            //查询all产品的价格
            DevicePrice devicePrice_all = devicePriceMapper.selectByAuthType(authType, DeviceProductEnum.ALL.getValue(), DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if (devicePrice_all == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置所有产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_all.getPrice());

            //分别查询ALL产品包含的产品的总价格
            Double price_total = 0.00D;
            for (String productCode : productCodeList) {
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }

            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);


            //封装机器人授权信息
            List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();

            //新增加时，只能买全包，计算是否需要补差价
            for (String productCode : productCodeList) {

                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(authType);
                deviceProductAuth.setExpireTime(expired_time);
                deviceProductAuth.setProductCode(productCode);
                deviceProductAuthList.add(deviceProductAuth);

                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器人手机端购买价格");
                }
                //产品单价
                Double product_price = Tools.getDouble(devicePrice.getPrice());
                //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));

                //总金额=单价*购买时间数
                Double amount = Math.mul(Tools.getDouble(product_price_discount), quantity, 2);
                //查询旧授权
                DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                //还未授权
                if (deviceAuth == null) {
                    //封装产品授权记录
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(merId);
                    deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceTypeKey);
                    deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(authType);
                    deviceAuthDetail.setQuantity(quantity_db);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                    deviceAuthDetail.setTradeno(trandeNo);
                    deviceAuthDetail.setRemark("余额支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetail.setAmount(amount);
                    deviceAuthDetail.setBeginTime(begin_time);
                    deviceAuthDetail.setExpireTime(expired_time);
                    //插入授权数据明细
                    deviceAuthDetailMapper.insert(deviceAuthDetail);

                    //插入授权数据
                    //添加机器人授权表
                    deviceAuth = new DeviceAuth();
                    deviceAuth.setId(IdWorker.getId());
                    deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuth.setDeviceType(deviceTypeKey);
                    deviceAuth.setDeviceTypeId(deviceTypeId);
                    deviceAuth.setAuthType(authType);
                    deviceAuth.setProductCode(productCode);
                    //新授权，到期时间从今天开始算
                    deviceAuth.setExpireTime(expired_time);
                    deviceAuth.setCreateTime(now);
                    deviceAuth.setUpdateTime(now);
                    deviceAuthMapper.insert(deviceAuth);

                } else { //授权存在，需判断授权的结束时间
                    //旧到期时间
                    Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                    //判断旧授权是否已经过期，
                    if (old_expireTime <= now) { //已经过期
                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                        deviceAuthDetail.setId(IdWorker.getId());
                        deviceAuthDetail.setMerId(merId);
                        deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuthDetail.setDeviceType(deviceTypeKey);
                        deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                        deviceAuthDetail.setProductCode(productCode);
                        deviceAuthDetail.setAuthType(authType);
                        deviceAuthDetail.setQuantity(quantity_db);
                        deviceAuthDetail.setPayTime(now);
                        deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                        deviceAuthDetail.setTradeno(trandeNo);
                        deviceAuthDetail.setRemark("余额支付");
                        deviceAuthDetail.setCreateTime(now);
                        deviceAuthDetail.setUpdateTime(now);
                        deviceAuthDetail.setAmount(amount);
                        deviceAuthDetail.setBeginTime(begin_time);
                        deviceAuthDetail.setExpireTime(expired_time);
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail);

                        //更新授权记录
                        deviceAuth.setExpireTime(expired_time);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);

                        //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                    } else if (old_expireTime > now && old_expireTime < expired_time) {
                        //需要补差价
                        Double differenceAmount = 0.00D;
                        //减去当前的时间，除以3600秒，再除以24小时取整，即是相差的天数
                        Double days = Math.div((old_expireTime - begin_time), 3600 * 24, 2);
                        if (deviceAuth.getAuthType().intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                            differenceAmount = Math.mul(Math.div(product_price_discount, 30), days, 2);
                            ;
                        } else {
                            differenceAmount = Math.mul(Math.div(product_price_discount, 360), days, 2);
                            ;
                        }
                        //单产品支付的金额
                        amount = Math.sub(amount, differenceAmount);

                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                        deviceAuthDetail.setId(IdWorker.getId());
                        deviceAuthDetail.setMerId(merId);
                        deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuthDetail.setDeviceType(deviceTypeKey);
                        deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                        deviceAuthDetail.setProductCode(productCode);
                        deviceAuthDetail.setAuthType(authType);
                        deviceAuthDetail.setQuantity(quantity_db);
                        deviceAuthDetail.setPayTime(now);
                        deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                        deviceAuthDetail.setTradeno(trandeNo);
                        deviceAuthDetail.setRemark("余额支付");
                        deviceAuthDetail.setCreateTime(now);
                        deviceAuthDetail.setUpdateTime(now);
                        deviceAuthDetail.setAmount(amount);
                        deviceAuthDetail.setBeginTime(begin_time);
                        deviceAuthDetail.setExpireTime(expired_time);
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail);
                        //更新授权记录
                        deviceAuth.setExpireTime(expired_time);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    }
                }
            }

            //添加redis缓存-机器人所属运营商
            Merchant device_merchant = new Merchant();
            device_merchant.setId(merchant.getId());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWechatInfo.getDeviceId()), Tools.getStrEmpty(JSONObject.toJSONString(device_merchant)));

            //更新机器人redis
            Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
            if (object != null) { //修改
                DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoMobileWeChatCacheDto.class);
                if (deviceInfoMobileWeChatCacheDto != null) {
                    deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                }
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
            } else {
                DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
                deviceInfoMobileWeChatCacheDto.setMerId(merId);
                deviceInfoMobileWeChatCacheDto.setDeviceId(deviceId);
                deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                }
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
            }

            //异步执行给机器人移动端APP授权
            deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceId, deviceWechatInfo.getRecvmsgType());


        } else {  //支付宝支付

            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(deviceWechatInfoAddDto.getMerId());
            alipayDetail.setTradeno(trandeNo);
            alipayDetail.setType(AlipayTypeEnum.DEVICE_MOBILE_ADD.getId()); //机器人授权
            //业务信息
            DeviceAddBusinessInfo deviceAddBusinessInfo = new DeviceAddBusinessInfo();
            deviceAddBusinessInfo.setDeviceId(deviceWechatInfoAddDto.getDeviceId());
            deviceAddBusinessInfo.setDeviceType(DeviceTypeEnum.DT_ANDROID_WECHAT.getKey());
            deviceAddBusinessInfo.setDeviceTypeId(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());
            deviceAddBusinessInfo.setAuthType(deviceWechatInfoAddDto.getAuthType());
            deviceAddBusinessInfo.setQuantity(quantity);
            deviceAddBusinessInfo.setAmount(amountTotal);
            alipayDetail.setBusinessInfo(Tools.getStrEmpty(JSONObject.toJSONString(deviceAddBusinessInfo)));
            alipayDetail.setAmount(amountTotal);
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            alipayDetailCreateDto.setSubject(AlipayTypeEnum.DEVICE_MOBILE_ADD.getDesc());
            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if (StringUtils.isNotBlank(alipayUrl)) {
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);

                deviceWechatInfoAddVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl() + "?id=" + alipayDetail.getId());
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        }

        return deviceWechatInfoAddVo;
    }

    /**
     * 添加机器人信息，创建订单
     *
     * @param deviceWechatInfoAddDto_new
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void addDeviceWechatInfo_new(DeviceWechatInfoAddDto_new deviceWechatInfoAddDto_new) {

        //查询账号信息
        Merchant merchant = merchantMapper.selectById(deviceWechatInfoAddDto_new.getMerId());
        if (merchant == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
        }

        DeviceWechatInfoAddVo deviceWechatInfoAddVo = new DeviceWechatInfoAddVo();
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        Integer now = DateUtil.getNowTime();
        Integer expired_time = now;
        Long merId = deviceWechatInfoAddDto_new.getMerId();

        //机器人类型id
        Integer deviceTypeId = deviceWechatInfoAddDto_new.getDeviceTypeId();
        if (deviceTypeId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型id");
        }

        if (deviceTypeId.intValue() != DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持添加机器人移动端");
        }

        //机器人类型key
        String deviceTypeKey = DeviceTypeEnum.getById(deviceTypeId).getKey();

        //机器人wxid
        String deviceId = deviceWechatInfoAddDto_new.getDeviceId();
        if (StringUtils.isBlank(deviceId)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人wxid");
        }

        boolean flag = StringUtils.isNumeric(deviceId);
        if (flag) {
            if(deviceId.length() == 16){
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人wxid不正确，个人机器人wxid不应该是16位纯数字");
            }
        }

        //选择该运营商默认配置方案
        ConfigPlan configPlan = configPlanMapper.selectByIsDefault(deviceWechatInfoAddDto_new.getMerId(), deviceTypeKey);
        if (configPlan == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商没有默认的配置方案");
        }

        //查询整个数据库当中正在使用的该微信id
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectByDeviceId(deviceId);
        //有在使用的机器人
        if (deviceWechatInfo != null) {
            //该机器人不属于自己运营商，则提示错误
            if (deviceWechatInfo.getMerId().longValue() != deviceWechatInfoAddDto_new.getMerId().longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该微信ID已经被其他运营商使用");
            }
        }

        //添加机器人只能试用全包套餐
        DeviceProduct deviceProduct_add = deviceProductMapper.selectByCode(DeviceProductEnum.ALL.getValue());
        if (deviceProduct_add == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置全包套餐");
        }

        //List<String> productCodeList = JSONObject.parseArray(deviceProduct_add.getCodes(), String.class);
        //从枚举中获取关联的产品
        DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_add.getCode());
        List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统全包套餐还没配置包含产品信息");
        }

        //是否新增机器人
        if (deviceWechatInfo == null) {//机器人为空，未还添加，则先添加机器人，默认配置方案
            //添加机器人
            deviceWechatInfo = new DeviceWechatInfo();
            deviceWechatInfo.setId(IdWorker.getId());
            deviceWechatInfo.setMerId(deviceWechatInfoAddDto_new.getMerId());
            deviceWechatInfo.setDeviceId(deviceWechatInfoAddDto_new.getDeviceId());
            deviceWechatInfo.setConfigId(configPlan.getId());
            deviceWechatInfo.setRecvmsgType(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());//移动端
            deviceWechatInfo.setDelStatus(DeleteStatusEnum.VALID.getId());//有效
            deviceWechatInfo.setCreateTime(now);
            deviceWechatInfo.setUpdateTime(now);
            //添加机器人
            deviceWechatInfoMapper.insert(deviceWechatInfo);

            //选择该运营商默认配置方案，需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
            if (configPlan.getOtherId() != null) {
                SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWechatInfoAddDto_new.getMerId());
                if (sysPlugin != null) {
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWechatInfo.getId()), sysPlugin.getData());
                }
            }
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该设备id是否已经授权过，如果没有，则开通试用期授权
        DeviceAuth deviceAuth_last = deviceAuthMapper.selectLastAuthByDeviceId(deviceId);
        if (deviceAuth_last == null) {//未开通过授权，则开通试用期权限
            expired_time = now + 5 * 24 * 3600;
            //新增加时，只能买全包，计算是否需要补差价
            for (String productCode : productCodeList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceProductAuth.setExpireTime(expired_time);
                deviceProductAuth.setProductCode(productCode);
                deviceProductAuthList.add(deviceProductAuth);

                //封装设备产品授权记录明细
                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                deviceAuthDetail.setId(IdWorker.getId());
                deviceAuthDetail.setMerId(merId);
                deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceAuthDetail.setDeviceType(deviceTypeKey);
                deviceAuthDetail.setDeviceTypeId(deviceTypeId);
                deviceAuthDetail.setProductCode(productCode);
                deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceAuthDetail.setQuantity(0); //试用为0
                deviceAuthDetail.setPayTime(now);
                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                deviceAuthDetail.setTradeno(trandeNo);
                deviceAuthDetail.setRemark("试用期");
                deviceAuthDetail.setCreateTime(now);
                deviceAuthDetail.setUpdateTime(now);
                deviceAuthDetail.setAmount(0.00);
                deviceAuthDetail.setBeginTime(now);
                deviceAuthDetail.setExpireTime(expired_time);
                //插入授权数据明细
                deviceAuthDetailMapper.insert(deviceAuthDetail);

                //添加机器人授权表
                DeviceAuth deviceAuth = new DeviceAuth();
                deviceAuth.setId(IdWorker.getId());
                deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                deviceAuth.setDeviceType(deviceTypeKey);
                deviceAuth.setDeviceTypeId(deviceTypeId);
                deviceAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
                deviceAuth.setProductCode(productCode);
                //新授权，到期时间从今天开始算
                deviceAuth.setExpireTime(expired_time);
                deviceAuth.setCreateTime(now);
                deviceAuth.setUpdateTime(now);
                deviceAuthMapper.insert(deviceAuth);
            }
            //异步执行给机器人移动端APP授权
            deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo.getDeviceId(), deviceWechatInfo.getRecvmsgType());
        } else {
            //刷新旧授权
            DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
            deviceAuthQuery.setDeviceId(deviceId);
            List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
            if (deviceAuthList != null && deviceAuthList.size() > 0) {
                for (DeviceAuth deviceAuth : deviceAuthList) {
                    //机器人redis缓存信息-产品授权
                    DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                    deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                    deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                    deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                    deviceProductAuthList.add(deviceProductAuth);
                }
            }

            //刷新授权APP信息
            expired_time = deviceAuth_last.getExpireTime();
            if (expired_time > now) { //授权未到期，则重新刷新授权APP信息
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceId, deviceWechatInfo.getRecvmsgType());
            }
        }

        //添加redis缓存-机器人所属运营商
        Merchant device_merchant = new Merchant();
        device_merchant.setId(merchant.getId());
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWechatInfo.getDeviceId()), Tools.getStrEmpty(JSONObject.toJSONString(device_merchant)));

        //发送切换设备端指令
        MsgDto msgDto = new MsgDto<>();
        msgDto.setContent("");
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CHANGE_DEVICE_MSG_HANDER.getValue());
        noticeMsgPushProducerService.sendDeviceMsgHander(msgDto);

        //更新机器人redis
        Object object = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        if (object != null) {//修改运营商信息
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object.toString(), DeviceInfoMobileWeChatCacheDto.class);
            if (deviceInfoMobileWeChatCacheDto != null) {
                deviceInfoMobileWeChatCacheDto.setMerId(merId);
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
            }
        } else {
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
            deviceInfoMobileWeChatCacheDto.setMerId(merId);
            deviceInfoMobileWeChatCacheDto.setDeviceId(deviceId);
            deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
            deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
        }

    }


    /**
     * 修改机器人信息
     *
     * @param deviceWechatInfoDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateDeviceWechatInfo(DeviceWechatInfoDto deviceWechatInfoDto) {

        if (deviceWechatInfoDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        if (deviceWechatInfoDto.getConfigId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择配置方案");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoDto.getId(), deviceWechatInfoDto.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //判断是否修改了配置方案id,如果修改了配置方案id,则需要判断配置方案里会员类型组是否不一样，如果不一样，则不能修改
        if (deviceWechatInfoDto.getConfigId().longValue() != Tools.getLong(deviceWechatInfo.getConfigId())) {
            ConfigPlan configPlanOld = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
            ConfigPlan configPlanNew = configPlanMapper.selectById(deviceWechatInfoDto.getConfigId(), deviceWechatInfoDto.getMerId());
            if (configPlanOld != null && configPlanNew != null) {
                if (Tools.getLong(configPlanOld.getUserTypeGroupId()).longValue() != Tools.getLong(configPlanNew.getUserTypeGroupId()).longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新修改的配置方案里的会员类型组和旧配置方案里会员类型组不一样");
                }
            }
        }

        Integer now = DateUtil.getNowTime();
        deviceWechatInfo.setDeviceName(deviceWechatInfoDto.getDeviceName());
        deviceWechatInfo.setDeviceRemark(deviceWechatInfoDto.getDeviceRemark());
        deviceWechatInfo.setGroupId(deviceWechatInfoDto.getGroupId());
        deviceWechatInfo.setConfigId(deviceWechatInfoDto.getConfigId());
        deviceWechatInfo.setUpdateTime(now);
        deviceWechatInfo.setAutoReplace(Tools.getInteger(deviceWechatInfoDto.getAutoReplace()));
        deviceWechatInfo.setConfigRule(deviceWechatInfoDto.getConfigRule());
        deviceWechatInfo.setMobile(deviceWechatInfoDto.getMobile());
        deviceWechatInfo.setMobiletype(deviceWechatInfoDto.getMobiletype());
        deviceWechatInfoMapper.updateById(deviceWechatInfo);

        //更新redis
        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfoDto.getId()));
        if (object_pc != null) {
            JSONObject jsonObject = JSONObject.parseObject(object_pc.toString());
            jsonObject.put("configId", deviceWechatInfoDto.getConfigId());
            jsonObject.put("deviceRemark", deviceWechatInfoDto.getDeviceRemark());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfoDto.getId()), jsonObject.toJSONString());
        }
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfoDto.getId()));
        if (object_mobile != null) {
            JSONObject jsonObject = JSONObject.parseObject(object_mobile.toString());
            jsonObject.put("configId", deviceWechatInfoDto.getConfigId());
            jsonObject.put("deviceRemark", deviceWechatInfoDto.getDeviceRemark());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfoDto.getId()), jsonObject.toJSONString());
        }

        //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
        ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
        if (configPlan != null && configPlan.getOtherId() != null) {
            SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWechatInfoDto.getMerId());
            if (sysPlugin != null) {
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWechatInfo.getId()), sysPlugin.getData());
            }
        }
    }

    /**
     * 批量修改机器人信息
     *
     * @param deviceWechatInfoBatchDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void batchUpdateDeviceWechatInfo(DeviceWechatInfoBatchDto deviceWechatInfoBatchDto) {

        if (deviceWechatInfoBatchDto.getIdList() == null || deviceWechatInfoBatchDto.getIdList().size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        Long configId = deviceWechatInfoBatchDto.getConfigId();
        ConfigPlan configPlan = null;
        if (configId != null) {
            configPlan = configPlanMapper.selectById(configId, deviceWechatInfoBatchDto.getMerId());
            if (configPlan == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该配置方案不存在");
            }
        }

        Long groupId = deviceWechatInfoBatchDto.getGroupId();
        if (groupId != null) {
            DeviceGroup deviceGroup = deviceGroupMapper.selectById(groupId, deviceWechatInfoBatchDto.getMerId());
            if (deviceGroup == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人分组不存在");
            }
        }

        //配置方案启用规则
        Integer configRule = deviceWechatInfoBatchDto.getConfigRule();

        for (Long id : deviceWechatInfoBatchDto.getIdList()) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoBatchDto.getMerId());
            if (deviceWechatInfo == null) {
                continue;
            }

            //判断是否修改了配置方案id,如果修改了配置方案id,则需要判断配置方案里会员类型组是否不一样，如果不一样，则不能修改
            if (Tools.getLong(deviceWechatInfoBatchDto.getConfigId()).longValue() != Tools.getLong(deviceWechatInfo.getConfigId())) {
                ConfigPlan configPlanOld = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
                ConfigPlan configPlanNew = configPlanMapper.selectById(deviceWechatInfoBatchDto.getConfigId(), deviceWechatInfoBatchDto.getMerId());
                if (configPlanOld != null && configPlanNew != null) {
                    if (Tools.getLong(configPlanOld.getUserTypeGroupId()).longValue() != Tools.getLong(configPlanNew.getUserTypeGroupId()).longValue()) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人id:" + deviceWechatInfo.getId() + "新修改的配置方案里的会员类型组和旧配置方案里会员类型组不一样");
                    }
                }
            }

            Integer now = DateUtil.getNowTime();

            if (configId != null) {
                deviceWechatInfo.setConfigId(configId);
            }

            if (groupId != null) {
                deviceWechatInfo.setGroupId(groupId);
            }

            if (configRule != null) {
                deviceWechatInfo.setConfigRule(configRule);
            }

            deviceWechatInfo.setUpdateTime(now);
            deviceWechatInfo.setAutoReplace(Tools.getInteger(deviceWechatInfoBatchDto.getAutoReplace()));
            deviceWechatInfoMapper.updateById(deviceWechatInfo);

            //更新redis
            if (configId != null) {
                Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), id));
                if (object_pc != null) {
                    JSONObject jsonObject = JSONObject.parseObject(object_pc.toString());
                    jsonObject.put("configId", deviceWechatInfoBatchDto.getConfigId());
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), id), jsonObject.toJSONString());
                }
                Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), id));
                if (object_mobile != null) {
                    JSONObject jsonObject = JSONObject.parseObject(object_mobile.toString());
                    jsonObject.put("configId", deviceWechatInfoBatchDto.getConfigId());
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), id), jsonObject.toJSONString());
                }

                //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                if (configPlan != null && configPlan.getOtherId() != null) {
                    //需要将配置方案当中的其他信息添加到Redis当中得 设备消息回复配置信息
                    SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getOtherId(), deviceWechatInfoBatchDto.getMerId());
                    if (sysPlugin != null) {
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_MSG_CONFIG.getKey(), deviceWechatInfo.getId()), sysPlugin.getData());
                    }
                }
            }
        }
    }

    /**
     * 个人微信机器人删除
     *
     * @param deviceWechatInfoDelDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public Boolean delDeviceWechatInfo(DeviceWechatInfoDelDto deviceWechatInfoDelDto) {

        //主键idList
        List<Long> idList = deviceWechatInfoDelDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }
        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoDelDto.getMerId());
            if (deviceWechatInfo != null) {
                deviceWechatInfoMapper.deleteById(id, deviceWechatInfoDelDto.getMerId());

                //删除该机器人的授权
                deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWechatInfo.getDeviceId());

                //清除机器人所有运营商缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWechatInfo.getDeviceId()));
                //删除机器人移动端缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                //删除机器人PC端缓存
                redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                //清除机器人ES通讯录
                wxContactsService.deleteWxContactsByDeviceUniqueId(deviceWechatInfo.getId(), deviceWechatInfo.getMerId());
            }
        }
        return true;
    }

    /**
     * 更新电脑端客户端软件
     *
     * @param deviceWechatInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updatePcClientSoft(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //从缓存中换取个人微信PC端信息
        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);

        //PC端个人微信信息不为空
        if (deviceInfoPcWeChatCacheDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "电脑端机器人还未曾登录过，不能更新版本");
        }

        //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
        Integer updateClientVersionStatus = deviceInfoPcWeChatCacheDto.getUpdateClientVersionStatus();
        Integer updateClientVersionTime = deviceInfoPcWeChatCacheDto.getUpdateClientVersionTime();
        if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
            if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人版本正在更新中 ，请稍后再试");
            }
        }

        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
        if (deviceVersion == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人最新版本为空");
        }

        //发送MQ消息
        MsgDto<UpdateClientAppDto> msgDto = new MsgDto<>();
        UpdateClientAppDto updateClientAppDto = new UpdateClientAppDto();
        msgDto.setContent(updateClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.UPDATE_CLIENT.getValue());
        updateClientAppDto.setUpdateType(1); //常规更新
        updateClientAppDto.setIsRunApp(1);   //启动
        updateClientAppDto.setNewVersion(deviceVersion.getVersion());
        noticeMsgPushProducerService.updateClientApp(msgDto);

        //修改Redis状态
        deviceInfoPcWeChatCacheDto.setUpdateClientVersionStatus(2);
        deviceInfoPcWeChatCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
    }

    /**
     * 批量更新电脑端客户端软件
     *
     * @param deviceWechatInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchUpdatePcClientSoft(DeviceWechatInfoIdListDto deviceWechatInfoIdListDto) {

        List<Long> idList = deviceWechatInfoIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoIdListDto.getMerId());
            if (deviceWechatInfo == null) {
                continue;
            }

            //从缓存中换取个人微信PC端信息
            Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);

            //PC端个人微信信息不为空
            if (deviceInfoPcWeChatCacheDto == null) {
                continue;
            }

            //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
            Integer updateClientVersionStatus = deviceInfoPcWeChatCacheDto.getUpdateClientVersionStatus();
            Integer updateClientVersionTime = deviceInfoPcWeChatCacheDto.getUpdateClientVersionTime();
            if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
                if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                    continue;
                }
            }

            DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
            if (deviceVersion == null) {
                continue;
            }


            //发送MQ消息
            MsgDto<UpdateClientAppDto> msgDto = new MsgDto<>();
            UpdateClientAppDto updateClientAppDto = new UpdateClientAppDto();
            msgDto.setContent(updateClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(deviceWechatInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.UPDATE_CLIENT.getValue());
            updateClientAppDto.setUpdateType(1); //强制更新
            updateClientAppDto.setIsRunApp(1);   //启动
            updateClientAppDto.setNewVersion(deviceVersion.getVersion());
            noticeMsgPushProducerService.updateClientApp(msgDto);

            //修改Redis状态
            deviceInfoPcWeChatCacheDto.setUpdateClientVersionStatus(2);
            deviceInfoPcWeChatCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
        }


    }

    /**
     * 重启电脑端客户端软件
     *
     * @param deviceWechatInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void restartPcClientSoft(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(2); //重启客户端软件
        noticeMsgPushProducerService.closeClientApp(msgDto);

    }

    /**
     * 批量重启电脑端客户端软件
     *
     * @param deviceWechatInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchRestartPcClientSoft(DeviceWechatInfoIdListDto deviceWechatInfoIdListDto) {
        List<Long> idList = deviceWechatInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoIdListDto.getMerId());
            if (deviceWechatInfo == null) {
                continue;
            }
            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(deviceWechatInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(2); //重启客户端软件
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 退出电脑端客户端软件
     *
     * @param deviceWechatInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void quitPcClientSoft(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(4); //退出客户端软件
        noticeMsgPushProducerService.closeClientApp(msgDto);
    }

    /**
     * 批量退出电脑端客户端软件
     *
     * @param deviceWechatInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchQuitPcClientSoft(DeviceWechatInfoIdListDto deviceWechatInfoIdListDto) {
        List<Long> idList = deviceWechatInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoIdListDto.getMerId());
            if (deviceWechatInfo == null) {
                continue;
            }
            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(deviceWechatInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(4); //退出客户端软件
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 退出电脑端微信
     *
     * @param deviceWechatInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void quitPcWechat(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //发送MQ消息
        MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
        CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
        msgDto.setContent(closeClientAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
        closeClientAppDto.setOptType(5); //退出电脑端微信
        noticeMsgPushProducerService.closeClientApp(msgDto);
    }

    /**
     * 批量退出电脑端微信
     *
     * @param deviceWechatInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchQuitPcWechat(DeviceWechatInfoIdListDto deviceWechatInfoIdListDto) {
        List<Long> idList = deviceWechatInfoIdListDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoIdListDto.getMerId());

            if (deviceWechatInfo == null) {
                continue;
            }

            //发送MQ消息
            MsgDto<CloseClientAppDto> msgDto = new MsgDto<>();
            CloseClientAppDto closeClientAppDto = new CloseClientAppDto();
            msgDto.setContent(closeClientAppDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
            msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
            msgDto.setMerId(deviceWechatInfo.getMerId());
            msgDto.setMsgType(MessageFuncEnum.CLOSE_CLIENT_APP.getValue());
            closeClientAppDto.setOptType(5); //退出电脑端微信
            noticeMsgPushProducerService.closeClientApp(msgDto);
        }
    }

    /**
     * 修改工作状态
     *
     * @param deviceWechatRecvmsgTypeDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateRecvmsgType(DeviceWechatRecvmsgTypeDto deviceWechatRecvmsgTypeDto) {
        if (deviceWechatRecvmsgTypeDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatRecvmsgTypeDto.getId(), deviceWechatRecvmsgTypeDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }



//        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
//        deviceAuthQuery.setDeviceId(deviceWechatInfo.getDeviceId());
//        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
//        if (deviceAuthList == null || deviceAuthList.size() == 0) {
//            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该端还未任何产品授权，不能切换");
//        }

        //修改个人微信机器人信息
        Integer now = DateUtil.getNowTime();
        deviceWechatInfo.setRecvmsgType(deviceWechatRecvmsgTypeDto.getRecvmsgType());
        deviceWechatInfo.setUpdateTime(now);
        deviceWechatInfoMapper.updateByIdSelective(deviceWechatInfo);

        if (deviceWechatRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
            //则将PC端授权卡密设置成到期
            //查询该设备微信id是否已经授权，如果存在，则需要将到期日修改成过期
//            CdkeysMobileApp cdkeysMobileApp = cdkeysMobileAppMapper.selectByDeviceId(deviceWechatInfo.getDeviceId());
//            if(cdkeysMobileApp != null) {//存在，表示已经授权过，刷新授权即可
//                cdkeysMobileApp.setExpireTime(now);
//                cdkeysMobileApp.setUpdateTime(now);
//                int i = cdkeysMobileAppMapper.updateById(cdkeysMobileApp);
//                if (i != 1) {
//                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络繁忙，请稍后再试");
//                }
//            }

            //删除该机器人的授权
            deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWechatInfo.getDeviceId());
        } else {
            //有授权才能却换
//            DeviceAuth deviceAuth = deviceAuthMapper.selectLastAuthByDeviceId(deviceWechatInfo.getDeviceId());
//            if (deviceAuth != null) {
                //异步执行给机器人移动端APP授权
                String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo.getDeviceId(), deviceWechatInfo.getRecvmsgType());
//            }
        }

        //发送切换设备端指令
        MsgDto msgDto = new MsgDto<>();
        msgDto.setContent("");
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.CHANGE_DEVICE_MSG_HANDER.getValue());
        noticeMsgPushProducerService.sendDeviceMsgHander(msgDto);

        //修改redis
        //获取PC端cache,如果有，则修改
        Object cache_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
        if (cache_pc != null) {
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(cache_pc), DeviceInfoPcWeChatCacheDto.class);
            if (deviceInfoPcWeChatCacheDto != null) {
                if (deviceWechatRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
                    deviceInfoPcWeChatCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoPcWeChatCacheDto.setMsgHandler(0);
                }
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
            }
        }

        //获取移动端cache,如果有，则修改
        Object cache_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        if (cache_mobile != null) {
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(cache_mobile), DeviceInfoMobileWeChatCacheDto.class);
            if (deviceInfoMobileWeChatCacheDto != null) {
                if (deviceWechatRecvmsgTypeDto.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                }
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
            }
        }
    }

    /**
     * 批量修改工作状态
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param deviceWechatRecvmsgTypeBatchDto
     * @return null
     */
    public void batchUpdateRecvmsgType(DeviceWechatRecvmsgTypeBatchDto deviceWechatRecvmsgTypeBatchDto){
        List<Long> idList = deviceWechatRecvmsgTypeBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        for (Long id : idList) {
            try {
                DeviceWechatRecvmsgTypeDto deviceWechatRecvmsgTypeDto = new DeviceWechatRecvmsgTypeDto();
                deviceWechatRecvmsgTypeDto.setMerId(deviceWechatRecvmsgTypeBatchDto.getMerId());
                deviceWechatRecvmsgTypeDto.setId(id);
                deviceWechatRecvmsgTypeDto.setRecvmsgType(deviceWechatRecvmsgTypeBatchDto.getRecvmsgType());
                updateRecvmsgType(deviceWechatRecvmsgTypeDto);
            }catch (Exception e){
                logger.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 购买授权
     *
     * @param deviceWechatInfoBuyAuthDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public DeviceWechatInfoAddVo buyDeviceAuth(DeviceWechatInfoBuyAuthDto deviceWechatInfoBuyAuthDto) {

        //判断是否已经实名验证
        RealNameVerificationJson realNameVerificationJson = merchantService.getRealNameInfo(deviceWechatInfoBuyAuthDto.getMerId());
        if (realNameVerificationJson == null || StringUtils.isBlank(realNameVerificationJson.getIdCard())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "需要验证运营商是否实名，未实名需要到【账号设置】中设置实名信息");
        }

        DeviceWechatInfoAddVo deviceWechatInfoAddVo = new DeviceWechatInfoAddVo();
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();
        Integer now = DateUtil.getNowTime();
        Long merId = deviceWechatInfoBuyAuthDto.getMerId();

        //取出机器人列表
        List<Long> idList = deviceWechatInfoBuyAuthDto.getIdList();
        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择设备id");
        }

        //支付类型
        Integer payType = deviceWechatInfoBuyAuthDto.getPayType();
        if (payType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付类型");
        }

        //购买产品
        String productCode_auth = deviceWechatInfoBuyAuthDto.getProductCode();
        if (StringUtils.isBlank(productCode_auth)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择授权产品");
        }
        DeviceProduct deviceProduct_auth = deviceProductMapper.selectByCode(productCode_auth);
        if (deviceProduct_auth == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置该设备产品功能");
        }

        //List<String> productCodeList = JSONObject.parseArray(deviceProduct_auth.getCodes(), String.class);

        //从枚举中获取关联的产品
        DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_auth.getCode());
        List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还没配置该设备产品功能");
        }

        //判断支付类型
        if (payType.intValue() == PaymentTypeEnum.PAY_BALANCE.getId().intValue()) {//余额支付

            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceWechatInfoBuyAuthDto.getAuthType();
            if (authType == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
            }

            //授权数量
            Integer quantity = deviceWechatInfoBuyAuthDto.getQuantity();
            if (quantity == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
            }

            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
                if (quantity.intValue() > 120) { //不能超过120月
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
                }
            } else { //按年购买
                if (quantity.intValue() > 10) { //不能超过10年
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
                }
            }

            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;

            //总金额
            DeviceAmountDto deviceAmountDto = new DeviceAmountDto();
            BeanUtils.copyProperties(deviceWechatInfoBuyAuthDto, deviceAmountDto);
            deviceAmountDto.setIdList(idList);
            deviceAmountDto.setOperType(2); //购买授权
            DeviceAmountVo deviceAmountVo = getAmount(deviceAmountDto);
            Double amountTotal = Tools.getDouble(deviceAmountVo.getAmountTotal());

            if (amountTotal.doubleValue() <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择授权时长已经存在");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if (devicePrice_buy == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for (String productCode : productCodeList) {
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);


            //新的到期时间
            Integer expired_time = 0;

            //保存账户余额
            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(merId);
            if (merchant == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }

            //判断余额大小
            Double balance = merchant.getBalance();
            if (balance.doubleValue() < amountTotal.doubleValue()) { //不够支付
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance - amountTotal);
            merchant.setUpdateTime(now);
            merchantMapper.updateBalance(merchant);

            //添加账户明细
            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(amountTotal);
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.DEVICE_PC_AUTH.getId());
            merAccDetail.setSubtype(productCode_auth);
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //循环批量操作的机器人
            for (Long deviceUniqueId : idList) {

                //查询机器人信息
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, deviceWechatInfoBuyAuthDto.getMerId());
                if (deviceWechatInfo == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的机器人不存在");
                }
                String deviceId = deviceWechatInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                } else {//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if (productCodeList.size() == 1) { //单个基础包，则需重新设置到期时间，直接时间累加
                    Integer beginTime_one = 0;
                    Integer expireTime_one = 0;
                    String productCode = productCodeList.get(0);

                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    if (deviceAuth != null) {//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if (old_expireTime <= now) {//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        } else {
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.updateById(deviceAuth);
                    } else {
                        deviceAuth = new DeviceAuth();
                        deviceAuth.setId(IdWorker.getId());
                        deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceAuth.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                        deviceAuth.setDeviceTypeId(deviceWechatInfoBuyAuthDto.getDeviceTypeId());
                        deviceAuth.setProductCode(productCode);
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        deviceAuth.setExpireTime(expireTime_one);
                        deviceAuth.setCreateTime(now);
                        deviceAuth.setUpdateTime(now);
                        deviceAuth.setAuthType(authType);
                        deviceAuthMapper.insert(deviceAuth);
                    }

                    //添加机器人授权明细表
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(deviceWechatInfoBuyAuthDto.getMerId());
                    deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                    deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                    deviceAuthDetail.setDeviceTypeId(deviceWechatInfoBuyAuthDto.getDeviceTypeId());
                    deviceAuthDetail.setProductCode(productCode);
                    deviceAuthDetail.setAuthType(deviceWechatInfoBuyAuthDto.getAuthType());
                    deviceAuthDetail.setQuantity(quantity_db); //试用为0
                    deviceAuthDetail.setBeginTime(beginTime_one);
                    deviceAuthDetail.setExpireTime(expireTime_one);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(deviceWechatInfoBuyAuthDto.getPayType());
                    deviceAuthDetail.setTradeno(trandeNo);
                    deviceAuthDetail.setAmount(amountTotal);
                    deviceAuthDetail.setRemark("余额支付");
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetailMapper.insert(deviceAuthDetail);
                } else { //全包产品
                    for (String productCode : productCodeList) {
                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                        //还未授权
                        if (deviceAuth == null) {
                            //封装产品授权记录
                            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                            deviceAuthDetail.setId(IdWorker.getId());
                            deviceAuthDetail.setMerId(merId);
                            deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                            deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                            deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                            deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                            deviceAuthDetail.setProductCode(productCode);
                            deviceAuthDetail.setAuthType(authType);
                            deviceAuthDetail.setQuantity(quantity_db);
                            deviceAuthDetail.setPayTime(now);
                            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                            deviceAuthDetail.setTradeno(trandeNo);
                            deviceAuthDetail.setRemark("余额支付");
                            deviceAuthDetail.setCreateTime(now);
                            deviceAuthDetail.setUpdateTime(now);
                            deviceAuthDetail.setAmount(amountTotal);
                            deviceAuthDetail.setBeginTime(begin_time);
                            deviceAuthDetail.setExpireTime(expired_time);
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail);

                            //插入授权数据
                            //添加机器人授权表
                            deviceAuth = new DeviceAuth();
                            deviceAuth.setId(IdWorker.getId());
                            deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
                            deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
                            deviceAuth.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                            deviceAuth.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                            deviceAuth.setAuthType(authType);
                            deviceAuth.setProductCode(productCode);
                            //新授权，到期时间从今天开始算
                            deviceAuth.setExpireTime(expired_time);
                            deviceAuth.setCreateTime(now);
                            deviceAuth.setUpdateTime(now);
                            deviceAuthMapper.insert(deviceAuth);

                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期
                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(merId);
                                deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                                deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                                deviceAuthDetail.setTradeno(trandeNo);
                                deviceAuthDetail.setRemark("余额支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(amountTotal);
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);

                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);

                                //旧到期时间大于当前时间，且小于授权结束时间，则补差价
                            } else if (old_expireTime > now && old_expireTime < expired_time) {

                                //封装产品授权记录
                                DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                                deviceAuthDetail.setId(IdWorker.getId());
                                deviceAuthDetail.setMerId(merId);
                                deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                                deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
                                deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                                deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                                deviceAuthDetail.setProductCode(productCode);
                                deviceAuthDetail.setAuthType(authType);
                                deviceAuthDetail.setQuantity(quantity_db);
                                deviceAuthDetail.setPayTime(now);
                                deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_BALANCE.getId());
                                deviceAuthDetail.setTradeno(trandeNo);
                                deviceAuthDetail.setRemark("余额支付");
                                deviceAuthDetail.setCreateTime(now);
                                deviceAuthDetail.setUpdateTime(now);
                                deviceAuthDetail.setAmount(amountTotal);
                                deviceAuthDetail.setBeginTime(begin_time);
                                deviceAuthDetail.setExpireTime(expired_time);
                                //插入授权数据明细
                                deviceAuthDetailMapper.insert(deviceAuthDetail);
                                //更新授权记录
                                deviceAuth.setAuthType(authType);
                                deviceAuth.setExpireTime(expired_time);
                                deviceAuth.setUpdateTime(now);
                                deviceAuthMapper.updateById(deviceAuth);
                            }
                        }
                    }
                }

                //封装机器人授权信息
                List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
                //查询该机器人的所有产品授权信息
                DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
                deviceAuthQuery.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceAuthQuery.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
                if (deviceAuthList != null && deviceAuthList.size() > 0) {
                    for (DeviceAuth deviceAuth : deviceAuthList) {
                        //机器人redis缓存信息-产品授权
                        DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                        deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                        deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                        deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                        deviceProductAuthList.add(deviceProductAuth);
                    }

                    //更新PC端redis
                    Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                    if (object_pc != null) { //修改
                        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoPcWeChatCacheDto.class);
                        if (deviceInfoPcWeChatCacheDto != null) {
                            deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                    } else {//新增
                        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
                        deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                        deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                        deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
                            deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
                        } else {
                            deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
                        }
                        //更新PC端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
                    }

                    //更新移动端redis
                    Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                    if (object_moblie != null) { //修改
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWeChatCacheDto.class);
                        if (deviceInfoMobileWeChatCacheDto != null) {
                            deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

                    } else {
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
                        deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                        deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                        deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                        deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                        if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                            deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                        } else {
                            deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                        }
                        //更新移动端机器人redis
                        redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
                    }
                }

                //异步执行给机器人移动端APP授权
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceId, deviceWechatInfo.getRecvmsgType());
            }
        } else if (payType.intValue() == PaymentTypeEnum.PAY_ALIPAY.getId().intValue()) { //支付宝支付
            //授权类型(0试用;1月卡;2年卡)
            Integer authType = deviceWechatInfoBuyAuthDto.getAuthType();
            if (authType == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
            }

            //授权数量
            Integer quantity = deviceWechatInfoBuyAuthDto.getQuantity();
            if (quantity == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
            }

            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
                if (quantity.intValue() > 120) { //不能超过120月
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
                }
            } else { //按年购买
                if (quantity.intValue() > 10) { //不能超过10年
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
                }
            }

            //保存到数据库当中的购买月数，按年买需要乘以12月
            Integer quantity_db = 0;

            //总金额
            DeviceAmountDto deviceAmountDto = new DeviceAmountDto();
            BeanUtils.copyProperties(deviceWechatInfoBuyAuthDto, deviceAmountDto);
            deviceAmountDto.setIdList(idList);
            deviceAmountDto.setOperType(2); //购买授权
            DeviceAmountVo deviceAmountVo = getAmount(deviceAmountDto);
            Double amountTotal = Tools.getDouble(deviceAmountVo.getAmountTotal());

            if (amountTotal.doubleValue() <= 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择授权时长已经存在");
            }

            //新的到期时间
            Integer expired_time = 0;

            //添加支付宝账单
            AlipayDetail alipayDetail = new AlipayDetail();
            alipayDetail.setId(IdWorker.getId());
            alipayDetail.setMerId(deviceWechatInfoBuyAuthDto.getMerId());
            alipayDetail.setTradeno(trandeNo);
            if (deviceWechatInfoBuyAuthDto.getDeviceTypeId().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //pc端续费
                alipayDetail.setType(AlipayTypeEnum.DEVICE_PC_AUTH.getId()); //续费电脑端机器人
            } else { //手机端续费
                alipayDetail.setType(AlipayTypeEnum.DEVICE_MOBILE_AUTH.getId()); //续费电脑端机器人
            }
            alipayDetail.setSubtype(productCode_auth);

            //业务信息
            DeviceAuthBusinessInfo deviceAuthBusinessInfo = new DeviceAuthBusinessInfo();
            deviceAuthBusinessInfo.setDeviceUniqueIdList(deviceWechatInfoBuyAuthDto.getIdList());
            deviceAuthBusinessInfo.setDeviceType(DeviceTypeEnum.getById(deviceWechatInfoBuyAuthDto.getDeviceTypeId()).getKey());
            deviceAuthBusinessInfo.setDeviceTypeId(deviceWechatInfoBuyAuthDto.getDeviceTypeId());
            deviceAuthBusinessInfo.setAuthType(deviceWechatInfoBuyAuthDto.getAuthType());
            deviceAuthBusinessInfo.setQuantity(quantity);
            deviceAuthBusinessInfo.setAmount(amountTotal);
            deviceAuthBusinessInfo.setProductCode(productCode_auth);

            //查询产品价格
            DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode_auth, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if (devicePrice == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器该端的购买价格");
            }
            deviceAuthBusinessInfo.setPrice(devicePrice.getPrice());
            alipayDetail.setBusinessInfo(Tools.getStrEmpty(JSONObject.toJSONString(deviceAuthBusinessInfo)));

            alipayDetail.setAmount(amountTotal);
            alipayDetail.setStatus(AlipayStatusEnum.WAIT_BUYER_PAY.getId()); //等待付款
            alipayDetail.setCreateTime(now);
            alipayDetail.setUpdateTime(now);

            //请求支付宝申请订单
            AlipayDetailCreateDto alipayDetailCreateDto = new AlipayDetailCreateDto();
            alipayDetailCreateDto.setOutTradeNo(alipayDetail.getTradeno());
            alipayDetailCreateDto.setTotalAmount(alipayDetail.getAmount());
            if (deviceWechatInfoBuyAuthDto.getDeviceTypeId().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //pc端续费
                alipayDetailCreateDto.setSubject(AlipayTypeEnum.DEVICE_PC_AUTH.getDesc());
            } else { //手机端充值
                alipayDetailCreateDto.setSubject(AlipayTypeEnum.DEVICE_MOBILE_AUTH.getDesc());
            }

            String alipayUrl = alipayDetailService.createAlipayDetail(alipayDetailCreateDto);
            if (StringUtils.isNotBlank(alipayUrl)) {
                alipayDetail.setAlipayUrl(alipayUrl);
                //插入支付宝账单
                alipayDetailMapper.insertSelective(alipayDetail);
                //返回支付页面
                deviceWechatInfoAddVo.setAlipayUrl(uzaiConsoleSysConfig.getAlipayPaypageUrl() + "?id=" + alipayDetail.getId());
            } else {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用支付宝失败");
            }
        } else if (payType.intValue() == PaymentTypeEnum.PAY_CARDID.getId().intValue()) { //卡密支付
            //返回每个设备对于卡密的充值结果信息
            List<CardBuyResult> cardBuyResultList = new ArrayList<>();
            deviceWechatInfoAddVo.setCardBuyResultList(cardBuyResultList);
            //取出卡密列表
            List<String> cardList = deviceWechatInfoBuyAuthDto.getCardList();
            if (cardList == null || cardList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入卡密");
            }

            //循环设备id列表
            for (int i = 0; i < idList.size(); i++) {
                //卡密购买返回结果
                CardBuyResult cardBuyResult = new CardBuyResult();
                cardBuyResult.setMsg("购买失败");
                //先封装近返回list
                cardBuyResultList.add(cardBuyResult);

                try { //每个设备单独提交
                    Long deviceUniqueId = idList.get(i);
                    DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, merId);
                    if (deviceWechatInfo != null) {
                        cardBuyResult.setDeviceName(deviceWechatInfo.getDeviceName()); //返回设备昵称
                        if (i < cardList.size()) {
                            //取出对于下标的卡密
                            String card = cardList.get(i);
                            cardBuyResult.setCard(card);  //返回卡密信息
                            //查询该卡信息
                            Cdkeys cdkeys = cdkeysMapper.selectByCard(card);

                            if (cdkeys == null) {
                                cardBuyResult.setMsg("卡密错误");
                                continue;
                            }


                            if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.ALL.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.ALL.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 全部功能 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.FL.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.FL.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 返利 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.UZAICHAT.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.UZAICHAT.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 悠聊 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.PYQ.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.PYQ.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 朋友圈 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.FD.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.FD.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 社群群发 卡");
                                    continue;
                                }
                            } else if (cdkeys.getProductType().intValue() == CdkeysProductTypeEnum.TUO.getId().intValue()) {
                                if (!productCode_auth.equals(DeviceProductEnum.TUO.getValue())) {
                                    cardBuyResult.setMsg("卡密类型不一致，当前卡为 个人微信 气氛组 卡");
                                    continue;
                                }
                            }

                            if (Tools.getInteger(cdkeys.getDeviceTypeId()).intValue() != DeviceTypeEnum.DT_PC_WECHAT.getId()) {//个人微信PC端
                                cardBuyResult.setMsg("不是个人微信卡密");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.USED.getId().intValue()) {//卡密已使用
                                cardBuyResult.setMsg("卡密已使用");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.INVALID.getId().intValue()) {//卡密已作废
                                cardBuyResult.setMsg("卡密已作废");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.STOCK.getId().intValue()) {//卡密还未出库
                                cardBuyResult.setMsg("卡密还未出库");
                                continue;
                            }
                            if (cdkeys.getStatus().intValue() == CdkeysStatusEnum.OUTSTOCK.getId().intValue()) {//出库状态
                                deviceWechatInfoCardPayService.buyDeviceAuthByCard(deviceWechatInfo, DeviceTypeEnum.DT_PC_WECHAT.getId(), cdkeys, now, trandeNo, productCodeList);
                                cardBuyResult.setMsg("购买成功");
                            }
                        }
                    } else {
                        cardBuyResult.setMsg("机器人不存在");
                        continue;
                    }
                } catch (Exception e) {
                    logger.error("----机器人授权购买失败----error={}", e.getMessage());
                    cardBuyResult.setMsg("购买失败");
                }
            }
        }
        return deviceWechatInfoAddVo;
    }

    /**
     * 查询添加或者购买总金额
     *
     * @param deviceAmountDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public DeviceAmountVo getAmount(DeviceAmountDto deviceAmountDto) {

        //操作类型(1-添加机器人；2-购买授权)
        Integer operType = deviceAmountDto.getOperType();
        if (deviceAmountDto.getOperType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入操作类型");
        }

        //类型类型id（0-PC端；1-移动端）
        Integer deviceTypeId = deviceAmountDto.getDeviceTypeId();
        if (deviceTypeId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入机器人类型id");
        }

        //授权类型(1月卡;2年卡)
        Integer authType = deviceAmountDto.getAuthType();
        if (authType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
        }

        //购买时长
        Integer quantity = deviceAmountDto.getQuantity();
        if (quantity == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入购买时长");
        }

        if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) { //按月购买
            if (quantity.intValue() > 120) { //不能超过120月
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买月数不能超过120个月");
            }
        } else { //按年购买
            if (quantity.intValue() > 10) { //不能超过10年
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "最大购买年数不能超过10年");
            }
        }

        //保存到数据库当中的购买月数，按年买需要乘以12月
        Integer quantity_db = 0;

        //返回对象
        DeviceAmountVo deviceAmountVo = new DeviceAmountVo();

        //封装机器人授权信息
        List<DeviceAmountVo.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();

        if (operType.intValue() == 1) { //添加机器人

            if (deviceTypeId.intValue() != DeviceTypeEnum.DT_ANDROID_WECHAT.getId().intValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "仅支持添加机器人移动端");
            }

            //设备id
            String deviceId = deviceAmountDto.getDeviceId();

            //购买产品
            DeviceProduct deviceProduct_add = deviceProductMapper.selectByCode(DeviceProductEnum.ALL.getValue());
            if (deviceProduct_add == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置该产品功能");
            }

            //List<String> productCodeList = JSONObject.parseArray(deviceProduct_add.getCodes(), String.class);
            //从枚举中获取关联的产品
            DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_add.getCode());
            List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
            if (productCodeList == null || productCodeList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统全包套餐还没配置包含产品信息");
            }

            //查询all产品的价格
            DevicePrice devicePrice_all = devicePriceMapper.selectByAuthType(authType, DeviceProductEnum.ALL.getValue(), DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if (devicePrice_all == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置所有产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_all.getPrice());

            //分别查询ALL产品包含的产品的总价格
            Double price_total = 0.00D;
            for (String productCode : productCodeList) {
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }

            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            //当天时间
            Integer now = DateUtil.getNowTime();
            //总金额
            Double amount_totle = 0.00D;
            //新的到期时间
            Integer expired_time = 0;
            //本次授权开始时间默认为现在
            Integer begin_time = now;

            //设备号不为空，则开始时间为数据库中最早的授权时间
            if (StringUtils.isNotBlank(deviceId)) {
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList, now);
            }

            //到期时间
            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                //新的到期时间=现在+月数*30天*24小时*3600秒
                expired_time = begin_time + quantity * 30 * 24 * 3600;
            } else {//按年购买
                //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
            }

            //单个机器人总金额=单价*购买时间数
            Double amount = Math.mul(Tools.getDouble(devicePrice_all.getPrice()), quantity);
            if (StringUtils.isBlank(deviceId)) {
                //总金额累加
                amount_totle = Math.add(amount_totle, amount);
            } else { //需要判断是否补差价
                //新增加时，只能买全包，计算是否需要补差价
                for (String productCode : productCodeList) {
                    //查询产品价格
                    DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                    if (devicePrice == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器人手机端购买价格");
                    }
                    //产品单价
                    Double product_price = Tools.getDouble(devicePrice.getPrice());
                    //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                    Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));
                    //查询旧授权
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    //还未授权,不需要补差价
                    if (deviceAuth == null) {
                        //总金额累加
                        //amount_totle =  Math.add(amount_totle, amount);
                    } else { //授权存在，需判断授权的结束时间
                        //旧到期时间
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        //判断旧授权是否已经过期，
                        if (old_expireTime <= now) { //已经过期,不需要补差价
                            //总金额累加
                            //amount_totle = Math.add(amount_totle, amount);
                        } else if (old_expireTime > now && old_expireTime < expired_time) {//未过期，且小于授权到期时间，如果大于，则跳过不过授权
                            //需要补差价
                            Double differenceAmount = 0.00D;
                            //减去当前的时间，除以3600秒，再除以24小时取整，即是相差的天数
                            Double days = Math.div((old_expireTime - begin_time), 3600 * 24, 2);
                            if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                                differenceAmount = Math.mul(Math.div(product_price_discount, 30), days, 2);
                            } else {
                                differenceAmount = Math.mul(Math.div(product_price_discount, 360), days, 2);
                                ;
                            }
                            //单产品支付的金额
                            amount = Math.sub(amount, differenceAmount);
                        }
                    }
                }
                //总金额累加
                amount_totle = Math.add(amount_totle, amount);
            }
            deviceAmountVo.setAmountTotal(amount_totle);
        } else { //购买授权
            //设备id
            List<Long> idList = deviceAmountDto.getIdList();
            if (idList == null || idList.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择需要购买授权的机器人");
            }

            //购买产品
            String productCode_buy = deviceAmountDto.getProductCode();
            if (StringUtils.isBlank(productCode_buy)) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择购买产品功能");
            }
            DeviceProduct deviceProduct_buy = deviceProductMapper.selectByCode(productCode_buy);
            if (deviceProduct_buy == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置该产品功能");
            }
            //List<String> productCodeList_buy = JSONObject.parseArray(deviceProduct_buy.getCodes(), String.class);
            //从枚举中获取关联的产品
            DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceProduct_buy.getCode());
            List<String> productCodeList_buy = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
            if (productCodeList_buy == null || productCodeList_buy.size() == 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还没配置该产品功能信息");
            }

            //查询产品的总价格
            DevicePrice devicePrice_buy = devicePriceMapper.selectByAuthType(authType, productCode_buy, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
            if (devicePrice_buy == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置产品的价格");
            }
            //all产品
            Double price_all = Tools.getDouble(devicePrice_buy.getPrice());
            //分别查询该产品包含的产品的总价格
            Double price_total = 0.00D;
            for (String productCode : productCodeList_buy) {
                //查询产品价格
                DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                if (devicePrice == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统还未配置好产品的价格");
                }
                price_total = Math.add(price_total, Tools.getDouble(devicePrice.getPrice()));
            }
            //总单价的优惠
            Double price_discount = Math.sub(price_total, price_all);

            if (price_discount.doubleValue() < 0) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统产品价格设置错误");
            }

            //当天时间
            Integer now = DateUtil.getNowTime();
            //总金额
            Double amount_totle = 0.00D;
            //新的到期时间
            Integer expired_time = 0;

            //循环批量操作的机器人
            for (Long deviceUniqueId : idList) {

                //查询机器人信息
                DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceUniqueId, deviceAmountDto.getMerId());
                if (deviceWechatInfo == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的机器人不存在");
                }
                String deviceId = deviceWechatInfo.getDeviceId();

                //本次授权开始时间默认为现在
                Integer begin_time = now;

                //查询该设备最早授权时间,如果不为空，则取最早授权时间为本次授权开始时间
                begin_time = deviceAuthService.selectEarliestAuthByDeviceIdAndProductCodeList(deviceId, productCodeList_buy, now);

                //选择全包套餐包时的到期时间，如果单个基础包购买，则另外判断到期时间
                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId().intValue()) {//按月购买
                    //新的到期时间=现在+月数*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 30 * 24 * 3600;
                    quantity_db = quantity;
                } else {//按年购买
                    //新的到期时间=现在+年数*12月*30天*24小时*3600秒
                    expired_time = begin_time + quantity * 12 * 30 * 24 * 3600;
                    quantity_db = quantity * 12;
                }

                //判断购买的产品类型（全包类型需要补差价）
                if (productCodeList_buy.size() == 1) { //单个基础包，则需重新设置到期时间，直接时间累加
                    //单个产品授权开始时间
                    Integer beginTime_one = 0;
                    //单个产品授权结束时间
                    Integer expireTime_one = 0;
                    //单个产品授权天数
                    Integer authDays_one = quantity_db * 30;
                    String productCode = productCodeList_buy.get(0);
                    DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                    if (devicePrice == null) {
                        throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置机器人该端的购买价格");
                    }
                    //单个机器人总金额=单价*购买时间数
                    Double amount = Math.mul(Tools.getDouble(devicePrice.getPrice()), quantity);
                    //总金额累加
                    amount_totle = Math.add(amount_totle, amount);

                    //计算产品授权记录
                    //添加机器人授权表-如果没有则新增，有则修改
                    DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                    if (deviceAuth != null) {//修改
                        //判断旧到期时间是否已经过期
                        Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                        if (old_expireTime <= now) {//已经到期，则从今天开始算
                            beginTime_one = now;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        } else {
                            beginTime_one = old_expireTime;
                            expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                        }
                    } else {
                        beginTime_one = now;
                        expireTime_one = beginTime_one + quantity_db * 30 * 24 * 3600;
                    }

                    //机器人redis缓存信息-产品授权
                    DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                    deviceProductAuth.setAuthDays(authDays_one);
                    deviceProductAuth.setExpireTime(expireTime_one);
                    deviceProductAuth.setProductCode(productCode);
                    deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                    deviceProductAuthList.add(deviceProductAuth);

                } else { //全包产品
                    //单个机器人总金额=单价*购买时间数
                    Double amount = Math.mul(Tools.getDouble(devicePrice_buy.getPrice()), quantity);

                    for (String productCode : productCodeList_buy) {

                        //单个产品授权天数
                        Integer authDays_one = quantity_db * 30;

                        //查询产品价格
                        DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
                        if (devicePrice == null) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置个人微信机器该端的购买价格");
                        }

                        //产品单价
                        Double product_price = devicePrice.getPrice();
                        //计算优惠后的产品单价 = 单价- 单价/总价 * 总优惠价
                        Double product_price_discount = Math.sub(product_price, Math.mul(Math.div(product_price, price_total), price_discount, 2));

                        //查询旧授权
                        DeviceAuth deviceAuth = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceId, productCode);
                        //还未授权，不需要补差价
                        if (deviceAuth == null) {
                            //机器人redis缓存信息-产品授权
                            DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                            deviceProductAuth.setAuthDays(authDays_one);
                            deviceProductAuth.setExpireTime(expired_time);
                            deviceProductAuth.setProductCode(productCode);
                            deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                            deviceProductAuthList.add(deviceProductAuth);
                        } else { //授权存在，需判断授权的结束时间
                            //旧到期时间
                            Integer old_expireTime = Tools.getInteger(deviceAuth.getExpireTime());
                            //判断旧授权是否已经过期，
                            if (old_expireTime <= now) { //已经过期，不需要补差价
                                //机器人redis缓存信息-产品授权
                                DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                                deviceProductAuth.setAuthDays(authDays_one);
                                deviceProductAuth.setExpireTime(expired_time);
                                deviceProductAuth.setProductCode(productCode);
                                deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                                deviceProductAuthList.add(deviceProductAuth);
                            } else if (old_expireTime > now && old_expireTime < expired_time) {
                                //需要补差价
                                Double differenceAmount = 0.00D;
                                //减去当前的时间，除以3600秒，再除以24小时取整，即是相差的天数
                                Double days = Math.div((old_expireTime - begin_time), 3600 * 24, 2);
                                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                                    differenceAmount = Math.mul(Math.div(product_price_discount, 30), days, 2);
                                } else {
                                    differenceAmount = Math.mul(Math.div(product_price_discount, 360), days, 2);
                                }
                                //单产品支付的金额
                                amount = Math.sub(amount, differenceAmount);
                                //授权的天数
                                authDays_one = authDays_one - days.intValue();

                                //机器人redis缓存信息-产品授权
                                DeviceAmountVo.DeviceProductAuth deviceProductAuth = new DeviceAmountVo.DeviceProductAuth();
                                deviceProductAuth.setAuthDays(authDays_one);
                                deviceProductAuth.setExpireTime(expired_time);
                                deviceProductAuth.setProductCode(productCode);
                                deviceProductAuth.setProductName(DeviceProductKeyEnum.getDesc(productCode));
                                deviceProductAuthList.add(deviceProductAuth);
                            } else if (old_expireTime >= expired_time) {
                                //需要补差价
                                Double differenceAmount = 0.00D;
                                //全额退款
                                if (authType.intValue() == DeviceAuthTypeEnum.DAT_MONTH.getId()) {//按月购买的
                                    differenceAmount = Math.mul(Math.div(product_price_discount, 30), authDays_one, 2);
                                } else {
                                    differenceAmount = Math.mul(Math.div(product_price_discount, 360), authDays_one, 2);
                                }
                                //单产品支付的金额
                                amount = Math.sub(amount, differenceAmount);
                            }
                        }
                    }
                    //总金额累加
                    amount_totle = Math.add(amount_totle, amount);
                }
            }
            deviceAmountVo.setAmountTotal(amount_totle);
            deviceAmountVo.setDeviceProductAuthList(deviceProductAuthList);
        }
        return deviceAmountVo;
    }

    /**
     * 查询购买产品授权价格
     *
     * @param devicePriceDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public DevicePriceVo getDevicePrice(DevicePriceDto devicePriceDto) {

        //授权类型(1月卡;2年卡)
        Integer authType = devicePriceDto.getAuthType();
        if (authType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入授权类型");
        }

        String productCode = devicePriceDto.getProductCode();
        if (StringUtils.isBlank(productCode)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入产品编码");
        }

        //查询产品价格
        DevicePrice devicePrice = devicePriceMapper.selectByAuthType(authType, productCode, DeviceTypeEnum.DT_PC_WECHAT_VALUE);
        if (devicePrice == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该产品还未设置价格");
        }

        DevicePriceVo devicePriceVo = new DevicePriceVo();
        devicePriceVo.setPrice(devicePrice.getPrice());

        return devicePriceVo;
    }

    /**
     * 查询设备产品列表
     *
     * @param deviceProductQuery
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public List<DeviceProductVo> deviceProductList(DeviceProductQuery deviceProductQuery) {
        List<DeviceProductVo> deviceProductVoList = new ArrayList<>();

//        List<DeviceProduct>  deviceProductList = deviceProductMapper.findByList(deviceProductQuery);
//        if(deviceProductList != null && deviceProductList.size() > 0){
//            for (DeviceProduct deviceProduct : deviceProductList){
//                DeviceProductVo deviceProductVo = new DeviceProductVo();
//                BeanUtils.copyProperties(deviceProduct, deviceProductVo);
//                if(StringUtils.isNotBlank(deviceProduct.getCodes())){
//                    deviceProductVo.setCodeList(JSONObject.parseArray(deviceProduct.getCodes(), String.class));
//                }
//                deviceProductVoList.add(deviceProductVo);
//            }
//        }

        DeviceProductEnum[] deviceProductEnums = DeviceProductEnum.values();
        if (deviceProductEnums != null && deviceProductEnums.length > 0) {
            for (DeviceProductEnum deviceProductEnum : deviceProductEnums) {
                if (!DeviceProductEnum.BANTRANSFER.getValue().equals(deviceProductEnum.getValue())) {
                    DeviceProductVo deviceProductVo = new DeviceProductVo();
                    DeviceProduct deviceProduct = deviceProductMapper.selectByCode(deviceProductEnum.getValue());
                    if (deviceProduct != null) {
                        BeanUtils.copyProperties(deviceProduct, deviceProductVo);
                    }

                    deviceProductVo.setName(deviceProductEnum.getDesc());

                    if (StringUtils.isNotBlank(deviceProductEnum.getCodes())) {
                        deviceProductVo.setCodeList(JSONObject.parseArray(deviceProductEnum.getCodes(), String.class));
                    }
                    deviceProductVoList.add(deviceProductVo);
                }
            }
        }
        return deviceProductVoList;
    }

    /**
     * 机器人封号名片转发
     *
     * @param banTransferDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void banTranfer(BanTransferDto banTransferDto) {

        if (banTransferDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(banTransferDto.getId(), banTransferDto.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        if (banTransferDto.getBanFlag() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入是否封禁");
        }

        if (banTransferDto.getTransferDevcieUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入名片转发机器人");
        }

        DeviceWechatInfo deviceWechatInfo_transfer = deviceWechatInfoMapper.selectById(banTransferDto.getTransferDevcieUniqueId(), banTransferDto.getMerId());
        if (deviceWechatInfo_transfer == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名片转发机器人不存在");
        }

        if (banTransferDto.getTransferInfoList() == null || banTransferDto.getTransferInfoList().size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转发微信信息列表不能为空");
        }

        //更新redis
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), banTransferDto.getId()));
        if (object_mobile != null) {
            JSONObject jsonObject = JSONObject.parseObject(object_mobile.toString());
            jsonObject.put("banFlag", banTransferDto.getBanFlag());
            jsonObject.put("transferDevcieUniqueId", deviceWechatInfo_transfer.getId());
            jsonObject.put("transferDeviceId", deviceWechatInfo_transfer.getDeviceId());
            jsonObject.put("transferDeviceTypeId", deviceWechatInfo_transfer.getRecvmsgType());
            jsonObject.put("transferWxid", ""); //更新的时候，将旧版的微信id设置为空
            jsonObject.put("transferInfoList", banTransferDto.getTransferInfoList());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), banTransferDto.getId()), jsonObject.toJSONString());
        }
    }

    /**
     * 刷新手机卡密授权
     *
     * @param deviceWechatInfoIdDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void refreshMobileApp(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        if (deviceWechatInfo.getRecvmsgType().intValue() != 1) {//不是手机在线，不能刷新
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不是手机端在线");
        }

        //更新redis
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfoIdDto.getId()));
        if (object_mobile != null) {//表示有移动端授权
            DeviceAuth deviceAuth = deviceAuthMapper.selectLastAuthByDeviceId(deviceWechatInfo.getDeviceId());
            if (deviceAuth != null) {
                deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo.getDeviceId(), deviceWechatInfo.getRecvmsgType());
            }
        }
    }

    /**
     * 转移授权时间
     *
     * @param tranferAuthTimeDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void transferAuthTime(TranferAuthTimeDto tranferAuthTimeDto) {

        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

        int now = DateUtil.getNowTime();
        Long merId = tranferAuthTimeDto.getMerId();

        Long id = tranferAuthTimeDto.getId();
        Long transferIdForAuthTime = tranferAuthTimeDto.getTransferIdForAuthTime();
        Long transferIdForUserAndOrder = tranferAuthTimeDto.getTransferIdForUserAndOrder();
        Integer transferDataFlag = tranferAuthTimeDto.getTransferDataFlag();

        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择被转移机器人");
        }
        if (transferIdForAuthTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择新转移授权时间机器人");
        }

        if (id.longValue() == transferIdForAuthTime.longValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, tranferAuthTimeDto.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移机器人不存在");
        }

        DeviceWechatInfo deviceWechatInfo_transferForAuthTime = deviceWechatInfoMapper.selectById(transferIdForAuthTime, tranferAuthTimeDto.getMerId());
        if (deviceWechatInfo_transferForAuthTime == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移授权时间机器人不存在");
        }

        //查询被转机器人的授权记录
        //授权信息
        List<DeviceAuthVo> deviceAuthVoList = new ArrayList<>();
        DeviceAuthQuery deviceAuthQuer = new DeviceAuthQuery();
        deviceAuthQuer.setDeviceId(deviceWechatInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuer);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //到期时间
                Integer expiretime = Tools.getInteger(deviceAuth.getExpireTime());
                //计算出将要转移的时间
                int transferTime = expiretime.intValue() - now - 5 * 24 * 3600;
                if (expiretime.intValue() > now && transferTime > 0) {//未到期有授权, 且授权时间在5天后（转移授权时间要减去5天试用期）
                    //先将被转机器人的授权修改成现在到期
                    deviceAuth.setExpireTime(now);
                    deviceAuthMapper.updateById(deviceAuth);

                    //添加授权记录
                    DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
                    deviceAuthDetail.setId(IdWorker.getId());
                    deviceAuthDetail.setMerId(merId);
                    deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
                    deviceAuthDetail.setDeviceId(deviceAuth.getDeviceId());
                    deviceAuthDetail.setDeviceType(deviceAuth.getDeviceType());
                    deviceAuthDetail.setDeviceTypeId(deviceAuth.getDeviceTypeId());
                    deviceAuthDetail.setProductCode(deviceAuth.getProductCode());
                    deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                    deviceAuthDetail.setQuantity(0);
                    deviceAuthDetail.setPayTime(now);
                    deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                    deviceAuthDetail.setTradeno(trandeNo);
                    deviceAuthDetail.setRemark("机器人转移（转出），新机器人微信id:=" + deviceWechatInfo_transferForAuthTime.getDeviceId() + ";旧授权时间:=" + expiretime + ";转移时间:=" + transferTime);
                    deviceAuthDetail.setCreateTime(now);
                    deviceAuthDetail.setUpdateTime(now);
                    deviceAuthDetail.setAmount(0.00);
                    deviceAuthDetail.setBeginTime(now);
                    deviceAuthDetail.setExpireTime(deviceAuth.getExpireTime());
                    //插入授权数据明细
                    deviceAuthDetailMapper.insert(deviceAuthDetail);


                    //然后将新转移机器人的授权时间延长
                    DeviceAuth deviceAuth_transfer = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWechatInfo_transferForAuthTime.getDeviceId(), deviceAuth.getProductCode());
                    //先判断存不存在，不存在则新增，存在则延迟时间
                    if (deviceAuth_transfer != null) { //授权存在，还需要判断授权时间是否过去
                        Integer expireTime_transfer = Tools.getInteger(deviceAuth_transfer.getExpireTime());

                        //未过期，则直接添加授权时间插
                        if (expireTime_transfer - now > 0) {
                            deviceAuth_transfer.setExpireTime(expireTime_transfer.intValue() + transferTime);
                            deviceAuth_transfer.setUpdateTime(now);
                            deviceAuthMapper.updateById(deviceAuth_transfer);

                            //添加授权记录
                            DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                            deviceAuthDetail_transfer.setId(IdWorker.getId());
                            deviceAuthDetail_transfer.setMerId(merId);
                            deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                            deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                            deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                            deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                            deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                            deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                            deviceAuthDetail_transfer.setQuantity(0);
                            deviceAuthDetail_transfer.setPayTime(now);
                            deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                            deviceAuthDetail_transfer.setTradeno(trandeNo);
                            deviceAuthDetail_transfer.setRemark("机器人转移（转入），旧机器人微信id:=" + deviceWechatInfo.getDeviceId() + ";旧授权时间:=" + expireTime_transfer + ";转移时间:=" + transferTime);
                            deviceAuthDetail_transfer.setCreateTime(now);
                            deviceAuthDetail_transfer.setUpdateTime(now);
                            deviceAuthDetail_transfer.setAmount(0.00);
                            deviceAuthDetail_transfer.setBeginTime(now);
                            deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);

                        } else {//已过期，则直接将被转移机器人的授权到期时间减去5天（试用期）替换新机器人的授权到期时间
                            deviceAuth_transfer.setExpireTime(expiretime - 5 * 24 * 3600);
                            deviceAuth_transfer.setUpdateTime(now);
                            deviceAuthMapper.updateById(deviceAuth_transfer);

                            //添加授权记录
                            DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                            deviceAuthDetail_transfer.setId(IdWorker.getId());
                            deviceAuthDetail_transfer.setMerId(merId);
                            deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                            deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                            deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                            deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                            deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                            deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                            deviceAuthDetail_transfer.setQuantity(0);
                            deviceAuthDetail_transfer.setPayTime(now);
                            deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                            deviceAuthDetail_transfer.setTradeno(trandeNo);
                            deviceAuthDetail_transfer.setRemark("机器人转移，旧机器人微信id:=" + deviceWechatInfo.getDeviceId() + ";旧授权时间:=" + expireTime_transfer + ";转移时间:=" + transferTime);
                            deviceAuthDetail_transfer.setCreateTime(now);
                            deviceAuthDetail_transfer.setUpdateTime(now);
                            deviceAuthDetail_transfer.setAmount(0.00);
                            deviceAuthDetail_transfer.setBeginTime(now);
                            deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                            //插入授权数据明细
                            deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);
                        }
                    } else { //不存在
                        deviceAuth_transfer = new DeviceAuth();
                        deviceAuth_transfer.setId(IdWorker.getId());
                        deviceAuth_transfer.setDeviceId(deviceWechatInfo_transferForAuthTime.getDeviceId());
                        deviceAuth_transfer.setDeviceUniqueId(deviceWechatInfo_transferForAuthTime.getId());
                        deviceAuth_transfer.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
                        deviceAuth_transfer.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
                        deviceAuth_transfer.setProductCode(deviceAuth.getProductCode());
                        deviceAuth_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                        //已过期，则直接将被转移机器人的授权到期时间减去5天（试用期）替换新机器人的授权到期时间
                        deviceAuth_transfer.setExpireTime(expiretime - 5 * 24 * 3600);
                        deviceAuth_transfer.setCreateTime(now);
                        deviceAuth_transfer.setUpdateTime(now);
                        deviceAuthMapper.insertSelective(deviceAuth_transfer);

                        //封装产品授权记录
                        DeviceAuthDetail deviceAuthDetail_transfer = new DeviceAuthDetail();
                        deviceAuthDetail_transfer.setId(IdWorker.getId());
                        deviceAuthDetail_transfer.setMerId(merId);
                        deviceAuthDetail_transfer.setDeviceUniqueId(deviceAuth_transfer.getId());
                        deviceAuthDetail_transfer.setDeviceId(deviceAuth_transfer.getDeviceId());
                        deviceAuthDetail_transfer.setDeviceType(deviceAuth_transfer.getDeviceType());
                        deviceAuthDetail_transfer.setDeviceTypeId(deviceAuth_transfer.getDeviceTypeId());
                        deviceAuthDetail_transfer.setProductCode(deviceAuth_transfer.getProductCode());
                        deviceAuthDetail_transfer.setAuthType(DeviceAuthTypeEnum.DAT_TRANSFER.getId());
                        deviceAuthDetail_transfer.setQuantity(0);
                        deviceAuthDetail_transfer.setPayTime(now);
                        deviceAuthDetail_transfer.setPayType(PaymentTypeEnum.PAY_FREE.getId());
                        deviceAuthDetail_transfer.setTradeno(trandeNo);
                        deviceAuthDetail_transfer.setRemark("机器人转移，旧机器人微信id:" + deviceWechatInfo.getDeviceId() + ";旧授权时间:=0;转移时间:=" + transferTime);
                        deviceAuthDetail_transfer.setCreateTime(now);
                        deviceAuthDetail_transfer.setUpdateTime(now);
                        deviceAuthDetail_transfer.setAmount(0.00);
                        deviceAuthDetail_transfer.setBeginTime(now);
                        deviceAuthDetail_transfer.setExpireTime(deviceAuth_transfer.getExpireTime());
                        //插入授权数据明细
                        deviceAuthDetailMapper.insert(deviceAuthDetail_transfer);
                    }
                }
            }
        }

        //刷新新转移机器人的授权缓存
        flashDeviceAuth(deviceWechatInfo_transferForAuthTime);
        //增加新机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthAddSync(deviceWechatInfo_transferForAuthTime.getDeviceId(), deviceWechatInfo_transferForAuthTime.getRecvmsgType());
        //删除旧机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWechatInfo.getDeviceId());

        //转移会员和订单
        if (transferDataFlag != null && transferDataFlag.intValue() == 1) {
            if (transferIdForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择新转移会员订单机器人");
            }

            DeviceWechatInfo deviceWechatInfo_transferForUserAndOrder = deviceWechatInfoMapper.selectById(transferIdForUserAndOrder, tranferAuthTimeDto.getMerId());
            if (deviceWechatInfo_transferForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单机器人不存在");
            }

            if (id.longValue() == transferIdForUserAndOrder.longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
            }

            ConfigPlan configPlan_self = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
            if (configPlan_self == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移的机器人配置方案不存在");
            }

            ConfigPlan configPlan_transferForUserAndOrder = configPlanMapper.selectById(deviceWechatInfo_transferForUserAndOrder.getConfigId(), deviceWechatInfo_transferForUserAndOrder.getMerId());
            if (configPlan_transferForUserAndOrder == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人配置方案不存在");
            }

            if (Tools.getLong(configPlan_self.getUserTypeGroupId()).longValue() != Tools.getLong(configPlan_transferForUserAndOrder.getUserTypeGroupId()).longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人的会员类型组与旧的不一样");
            }

            //转移会员
            wechatUserMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(id, transferIdForUserAndOrder, merId);
        }


    }

    /**
     * 删除机器人且转移数据
     *
     * @param delAndTransferDataDto
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void delAndTransferData(DelAndTransferDataDto delAndTransferDataDto) {

        int now = DateUtil.getNowTime();
        Long merId = delAndTransferDataDto.getMerId();

        Long id = delAndTransferDataDto.getId();
        Long transferId = delAndTransferDataDto.getTransferId();

        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择将要删除的机器人");
        }
        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, delAndTransferDataDto.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "将要删除的机器人不存在");
        }

        //需要转移机器人，则必须要选择转移的新机器人
        if (transferId != null) {
            if (id.longValue() == transferId.longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不能是自己本身");
            }
            DeviceWechatInfo deviceWechatInfo_transfer = deviceWechatInfoMapper.selectById(transferId, delAndTransferDataDto.getMerId());
            if (deviceWechatInfo_transfer == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移机器人不存在");
            }

            ConfigPlan configPlan_self = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
            if (configPlan_self == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "被转移的机器人配置方案不存在");
            }

            ConfigPlan configPlan_transfer = configPlanMapper.selectById(deviceWechatInfo_transfer.getConfigId(), deviceWechatInfo_transfer.getMerId());
            if (configPlan_transfer == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人配置方案不存在");
            }

            if (Tools.getLong(configPlan_self.getUserTypeGroupId()).longValue() != Tools.getLong(configPlan_transfer.getUserTypeGroupId()).longValue()) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新转移会员订单的机器人的会员类型组与旧的不一样");
            }

            //转移会员
            wechatUserMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移淘宝订单
            tbOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移京东订单
            jdOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移拼多多订单
            pddOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移唯品会订单
            vphOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移美团订单
            mtOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
            //转移抖音订单
            dyOrderMapper.batchUpdateDeviceInfo(id, transferId, merId);
        }

        //删除该机器人
        deviceWechatInfoMapper.deleteById(id, delAndTransferDataDto.getMerId());
        //删除该机器人的授权
        deviceWechatInfoSyncService.mobiledeviceAuthDelSync(deviceWechatInfo.getDeviceId());

        //清除机器人所属运营商缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_MERCHANT.getKey(), deviceWechatInfo.getDeviceId()));
        //删除机器人移动端缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        //删除机器人PC端缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
        //清除机器人ES通讯录
        wxContactsService.deleteWxContactsByDeviceUniqueId(deviceWechatInfo.getId(), deviceWechatInfo.getMerId());

    }

    /**
     * 刷新在线状态
     *
     * @param merId
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void refreshOnlineStatus(Long merId) {
        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先登录");
        }
        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
        deviceWechatInfoQuery.setMerId(merId);
        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {

            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                try {

                    //PC端
                    deviceWechatInfo.setPcStatus(0); //默认离线
                    Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
                    if (object_pc != null) {
                        DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_pc), DeviceInfoPcWeChatCacheDto.class);
                        if (deviceInfoPcWeChatCacheDto != null) {
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoPcWeChatCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWechatInfo.setPcStatus(1); //在线
                                }
                            }
                        }
                    }

                    //移动端
                    deviceWechatInfo.setMobileStatus(0); //默认离线
                    Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
                    if (object_mobile != null) {
                        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);
                        //手机端个人微信信息不为空
                        if (deviceInfoMobileWeChatCacheDto != null) {
                            //获取最新心跳时间
                            Integer lastHeartBeatTime = deviceInfoMobileWeChatCacheDto.getLastHeartBeatTime();
                            if (lastHeartBeatTime != null) {
                                //判断在线（少于5分钟表示在线）
                                if (DateUtil.getNowTime() - lastHeartBeatTime < Const.Device.HEART_BEAT_OFF_LINE_TIME) {
                                    deviceWechatInfo.setMobileStatus(1); //在线
                                }
                            }
                        }
                    }

                    deviceWechatInfoMapper.updateOnlineStatus(deviceWechatInfo);

                } catch (Exception e) {

                }
            }
        }
    }

    /**
     * 查询个人微信机器人列表
     *
     * @param deviceWechatInfoQuery
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public List<DeviceWechatInfoVo> findDeviceWechatInfoSelect(DeviceWechatInfoQuery deviceWechatInfoQuery) {

        //手动处理机器人分页查询-如果是机器人昵称，则按照中文gbk排序
        List<OrderItem> orderItemList = deviceWechatInfoQuery.getOrderItemList();
        if (orderItemList != null && orderItemList.size() > 0) {
            for (OrderItem orderItem : orderItemList) {
                if ("deviceName".equals(orderItem.getColumn())) {
                    orderItem.setColumn(" convert( " + orderItem.getColumn() + " using gbk) ");
                }
            }
        }

        //新建返回到页面的LIST对象
        List<DeviceWechatInfoVo> deviceWechatInfoPageVoList = new ArrayList<>();

        ArrayList<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
        if (deviceWechatInfoList != null && deviceWechatInfoList.size() > 0) {
            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                DeviceWechatInfoVo deviceWechatInfoPageVo = new DeviceWechatInfoVo();
                BeanUtils.copyProperties(deviceWechatInfo, deviceWechatInfoPageVo);

                //机器人分组
                DeviceGroup deviceGroup = deviceGroupMapper.selectById(deviceWechatInfo.getGroupId(), deviceWechatInfo.getMerId());
                if (deviceGroup != null) {
                    deviceWechatInfoPageVo.setGroupName(deviceGroup.getName());
                }
                //获取配置方案信息
                ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
                if (configPlan != null) {
                    deviceWechatInfoPageVo.setConfigName(configPlan.getName());
                }
                deviceWechatInfoPageVoList.add(deviceWechatInfoPageVo);
            }
        }

        return deviceWechatInfoPageVoList;
    }

    /**
     * 更新手机版
     *
     * @param deviceWechatInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void updateMobileClientSoft(DeviceWechatInfoIdDto deviceWechatInfoIdDto) {
        if (deviceWechatInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoIdDto.getId(), deviceWechatInfoIdDto.getMerId());

        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人不存在");
        }

        //从缓存中换取个人微信移动端信息
        Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);

        //移动端个人微信信息不为空
        if (deviceInfoMobileWeChatCacheDto == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "移动端机器人还未曾登录过，不能更新版本");
        }

        //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
        Integer updateClientVersionStatus = deviceInfoMobileWeChatCacheDto.getUpdateClientVersionStatus();
        Integer updateClientVersionTime = deviceInfoMobileWeChatCacheDto.getUpdateClientVersionTime();
        if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
            if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人版本正在更新中 ，请稍后再试");
            }
        }

//        DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());
//        if(deviceVersion == null){
//            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "机器人最新版本为空");
//        }

        //从缓存中获取版本移动端版本信息
        Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.MOBILE_APP_UPDATE_INFO.getKey());
        if (object_mobile_version == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息未设置");
        }

        JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
        if (jsonObject == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息格式错误");
        }

        //软件版本号
        Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
        //软件版本名称
        String version = Tools.getStr(jsonObject.getString("version"));
        //包名称
        String packageName = Tools.getStr(jsonObject.getString("packageName"));
        //软件包URL地址
        String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));

        //发送微服务，通知终端
        MsgDto<UpdateAndroidAppDto> msgDto = new MsgDto<>();
        UpdateAndroidAppDto updateAndroidAppDto = new UpdateAndroidAppDto();
        msgDto.setContent(updateAndroidAppDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
        msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
        msgDto.setMerId(deviceWechatInfo.getMerId());
        msgDto.setMsgType(MessageFuncEnum.UPDATE_ANDROID_APP.getValue());
        //封装参数对象
        updateAndroidAppDto.setWechatId(deviceWechatInfo.getDeviceId());
        updateAndroidAppDto.setImei(deviceWechatInfo.getDeviceId());
        updateAndroidAppDto.setVerNumber(verNumber);
        updateAndroidAppDto.setVersion(version);
        updateAndroidAppDto.setPackageName(packageName);
        updateAndroidAppDto.setPackageUrl(packageUrl);
        UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.androidAppUpdate(msgDto);
        logger.info("---调用安卓APP版本更新接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
            //修改Redis状态
            deviceInfoMobileWeChatCacheDto.setUpdateClientVersionStatus(2);
            deviceInfoMobileWeChatCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
        }

    }

    /**
     * 批量更新手机版
     *
     * @param deviceWechatInfoIdListDto
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    public void batchUpdateMobileClientSoft(DeviceWechatInfoIdListDto deviceWechatInfoIdListDto) {

        List<Long> idList = deviceWechatInfoIdListDto.getIdList();

        if (idList == null || idList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id参数");
        }

        for (Long id : idList) {
            DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(id, deviceWechatInfoIdListDto.getMerId());
            if (deviceWechatInfo == null) {
                continue;
            }

            //从缓存中换取个人微信手机版端信息
            Object object_mobile = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(String.valueOf(object_mobile), DeviceInfoMobileWeChatCacheDto.class);

            //手机版个人微信信息不为空
            if (deviceInfoMobileWeChatCacheDto == null) {
                continue;
            }

            //更新客户端版本状态(0-无更新；1-有更新；2-更新中; 3-更新失败(当状态为2时，验证更新时间是否超过5分钟，超过就更新失败)")
            Integer updateClientVersionStatus = deviceInfoMobileWeChatCacheDto.getUpdateClientVersionStatus();
            Integer updateClientVersionTime = deviceInfoMobileWeChatCacheDto.getUpdateClientVersionTime();
            if (updateClientVersionStatus != null && updateClientVersionStatus.intValue() == 2) {
                if (DateUtil.getNowTime() - updateClientVersionTime < Const.Device.UPDATE_VERSION_VALIDITY_TIME) {
                    continue;
                }
            }

//            DeviceVersion deviceVersion = deviceVersionMapper.selectByTypeId(DeviceTypeEnum.DT_ANDROID_WECHAT.getId());
//            if(deviceVersion == null){
//                continue;
//            }

            //调用微服务通知移动端APP更新
            try {
                //从缓存中获取版本移动端版本信息
                Object object_mobile_version = redisTemplate.opsForValue().get(RedisCacheKeyEnum.MOBILE_APP_UPDATE_INFO.getKey());
                if (object_mobile_version == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息未设置");
                }

                JSONObject jsonObject = JSONObject.parseObject(object_mobile_version.toString());
                if (jsonObject == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端软件版本信息格式错误");
                }

                //软件版本号
                Integer verNumber = Tools.getInteger(jsonObject.getInteger("verNumber"));
                //软件版本名称
                String version = Tools.getStr(jsonObject.getString("version"));
                //包名称
                String packageName = Tools.getStr(jsonObject.getString("packageName"));
                //软件包URL地址
                String packageUrl = Tools.getStr(jsonObject.getString("packageUrl"));

                //发送微服务，通知终端
                MsgDto<UpdateAndroidAppDto> msgDto = new MsgDto<>();
                UpdateAndroidAppDto updateAndroidAppDto = new UpdateAndroidAppDto();
                msgDto.setContent(updateAndroidAppDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceType(deviceWechatInfo.getRecvmsgType());
                msgDto.setDeviceUniqueId(deviceWechatInfo.getId());
                msgDto.setMerId(deviceWechatInfo.getMerId());
                msgDto.setMsgType(MessageFuncEnum.UPDATE_ANDROID_APP.getValue());
                //封装参数对象
                updateAndroidAppDto.setWechatId(deviceWechatInfo.getDeviceId());
                updateAndroidAppDto.setImei(deviceWechatInfo.getDeviceId());
                updateAndroidAppDto.setVerNumber(verNumber);
                updateAndroidAppDto.setVersion(version);
                updateAndroidAppDto.setPackageName(packageName);
                updateAndroidAppDto.setPackageUrl(packageUrl);
                UzaiRespVo<Object> uzaiRespVo = uzaiImClientFeignService.androidAppUpdate(msgDto);
                logger.info("---调用安卓APP版本更新接口----para={},result={}", JSONObject.toJSONString(msgDto), JSONObject.toJSONString(uzaiRespVo));

                if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    //修改Redis状态
                    deviceInfoMobileWeChatCacheDto.setUpdateClientVersionStatus(2);
                    deviceInfoMobileWeChatCacheDto.setUpdateClientVersionTime(DateUtil.getNowTime());
                    redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
                }
            } catch (Exception e) {
            }
        }
    }

    /**
     * 增加试用期授权
     *
     * @param deviceWechatInfoAddProbationAuth
     * @return null
     * @author liuqi
     * @date 2021/8/13 11:38
     */
    @Transactional
    public void addProbationAuth(DeviceWechatInfoAddProbationAuth deviceWechatInfoAddProbationAuth) {

        Long merId = deviceWechatInfoAddProbationAuth.getMerId();

        if (merId == null
                || deviceWechatInfoAddProbationAuth.getId() == null
                || StringUtils.isBlank(deviceWechatInfoAddProbationAuth.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "参数不能为空");
        }

        DeviceWechatInfo deviceWechatInfo = deviceWechatInfoMapper.selectById(deviceWechatInfoAddProbationAuth.getId(), deviceWechatInfoAddProbationAuth.getMerId());
        if (deviceWechatInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该机器人唯一id不存在");
        }

        if (DeviceProductEnum.ALL.getValue().equals(deviceWechatInfoAddProbationAuth.getProductCode())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "目前还未支持增加此产品试用期授权");
        }

        DeviceProductEnum deviceProductEnum = DeviceProductEnum.getValue(deviceWechatInfoAddProbationAuth.getProductCode());

        if (deviceProductEnum == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该产品不存在");
        }

        List<String> productCodeList = JSONObject.parseArray(deviceProductEnum.getCodes(), String.class);
        if (productCodeList == null || productCodeList.size() == 0) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统未配置该产品信息");
        }

        //业务编码
        String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

        //当前时间
        int now = DateUtil.getNowTime();
        //产品到期时间=当前时间+5天
        int expired_time = now + Const.Device.DEVICE_DAT_FREE_DURATION * 24 * 3600;

        //新增加时，只能买全包，计算是否需要补差价
        for (String productCode : productCodeList) {

            DeviceAuth deviceAuth_old = deviceAuthMapper.selectByDeviceIdAndProductCode(deviceWechatInfo.getDeviceId(), productCode);
            if (deviceAuth_old != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该产品已经有授权记录，不能增加试用期授权");
            }

            //添加机器人授权表
            DeviceAuth deviceAuth = new DeviceAuth();
            deviceAuth.setId(IdWorker.getId());
            deviceAuth.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceAuth.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceAuth.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            deviceAuth.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
            deviceAuth.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
            deviceAuth.setProductCode(productCode);
            //新授权，到期时间从今天开始算
            deviceAuth.setExpireTime(expired_time);
            deviceAuth.setCreateTime(now);
            deviceAuth.setUpdateTime(now);
            deviceAuthMapper.insert(deviceAuth);

            //封装设备产品授权记录明细
            DeviceAuthDetail deviceAuthDetail = new DeviceAuthDetail();
            deviceAuthDetail.setId(IdWorker.getId());
            deviceAuthDetail.setMerId(merId);
            deviceAuthDetail.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceAuthDetail.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceAuthDetail.setDeviceType(DeviceTypeEnum.DT_PC_WECHAT.getKey());
            deviceAuthDetail.setDeviceTypeId(DeviceTypeEnum.DT_PC_WECHAT.getId());
            deviceAuthDetail.setProductCode(productCode);
            deviceAuthDetail.setAuthType(DeviceAuthTypeEnum.DAT_FREE.getId().intValue());
            deviceAuthDetail.setQuantity(0); //试用为0
            deviceAuthDetail.setPayTime(now);
            deviceAuthDetail.setPayType(PaymentTypeEnum.PAY_FREE.getId());
            deviceAuthDetail.setTradeno(trandeNo);
            deviceAuthDetail.setRemark("手动试用期授权");
            deviceAuthDetail.setCreateTime(now);
            deviceAuthDetail.setUpdateTime(now);
            deviceAuthDetail.setAmount(0.00);
            deviceAuthDetail.setBeginTime(now);
            deviceAuthDetail.setExpireTime(expired_time);
            //插入授权数据明细
            deviceAuthDetailMapper.insert(deviceAuthDetail);
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该机器人的所有产品授权信息
        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
        deviceAuthQuery.setDeviceId(deviceWechatInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }

            //更新PC端redis
            Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
            if (object_pc != null) { //修改
                DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoPcWeChatCacheDto.class);
                if (deviceInfoPcWeChatCacheDto != null) {
                    deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                }
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
            } else {//新增
                DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
                deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
                    deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
                } else {
                    deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
                }
                //更新PC端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
            }

            //更新移动端redis
            Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
            if (object_moblie != null) { //修改
                DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWeChatCacheDto.class);
                if (deviceInfoMobileWeChatCacheDto != null) {
                    deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                }
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

            } else {
                DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
                deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
                deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
                deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
                deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
                deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
                if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
                } else {
                    deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
                }
                //更新移动端机器人redis
                redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
            }
        }

    }

    //刷新个人微信机器人授权信息
    public void flashDeviceAuth(DeviceWechatInfo deviceWechatInfo, List<DeviceAuth> deviceAuthList) {

        if (deviceWechatInfo == null) {
            return;
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();

        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }
        }

        //更新PC端redis
        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
        if (object_pc != null) { //修改
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoPcWeChatCacheDto.class);
            if (deviceInfoPcWeChatCacheDto != null) {
                deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
        } else {//新增
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
            deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
            deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
            deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
                deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
            } else {
                deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
            }
            //更新PC端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
        }

        //更新移动端redis
        Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        if (object_moblie != null) { //修改
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWeChatCacheDto.class);
            if (deviceInfoMobileWeChatCacheDto != null) {
                deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

        } else {
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
            deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
            deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
            deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
        }
    }


    //刷新个人微信机器人授权信息
    public void flashDeviceAuth(DeviceWechatInfo deviceWechatInfo) {
        if (deviceWechatInfo == null) {
            return;
        }

        //封装机器人授权信息
        List<DeviceInfoBaseCache.DeviceProductAuth> deviceProductAuthList = new ArrayList<>();
        //查询该机器人的所有产品授权信息
        DeviceAuthQuery deviceAuthQuery = new DeviceAuthQuery();
        deviceAuthQuery.setDeviceId(deviceWechatInfo.getDeviceId());
        List<DeviceAuth> deviceAuthList = deviceAuthMapper.findByList(deviceAuthQuery);
        if (deviceAuthList != null && deviceAuthList.size() > 0) {
            for (DeviceAuth deviceAuth : deviceAuthList) {
                //机器人redis缓存信息-产品授权
                DeviceInfoBaseCache.DeviceProductAuth deviceProductAuth = new DeviceInfoBaseCache.DeviceProductAuth();
                deviceProductAuth.setAuthType(deviceAuth.getAuthType());
                deviceProductAuth.setExpireTime(deviceAuth.getExpireTime());
                deviceProductAuth.setProductCode(deviceAuth.getProductCode());
                deviceProductAuthList.add(deviceProductAuth);
            }
        }

        //更新PC端redis
        Object object_pc = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()));
        if (object_pc != null) { //修改
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = JSONObject.parseObject(object_pc.toString(), DeviceInfoPcWeChatCacheDto.class);
            if (deviceInfoPcWeChatCacheDto != null) {
                deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
        } else {//新增
            DeviceInfoPcWeChatCacheDto deviceInfoPcWeChatCacheDto = new DeviceInfoPcWeChatCacheDto();
            deviceInfoPcWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
            deviceInfoPcWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceInfoPcWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceInfoPcWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
            deviceInfoPcWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_PC_WECHAT.getId()) { //PC端接收消息
                deviceInfoPcWeChatCacheDto.setMsgHandler(1); //接收消息
            } else {
                deviceInfoPcWeChatCacheDto.setMsgHandler(0); //不接受消息
            }
            //更新PC端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_PC.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoPcWeChatCacheDto)));
        }

        //更新移动端redis
        Object object_moblie = redisTemplate.opsForValue().get(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()));
        if (object_moblie != null) { //修改
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = JSONObject.parseObject(object_moblie.toString(), DeviceInfoMobileWeChatCacheDto.class);
            if (deviceInfoMobileWeChatCacheDto != null) {
                deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));

        } else {
            DeviceInfoMobileWeChatCacheDto deviceInfoMobileWeChatCacheDto = new DeviceInfoMobileWeChatCacheDto();
            deviceInfoMobileWeChatCacheDto.setMerId(deviceWechatInfo.getMerId());
            deviceInfoMobileWeChatCacheDto.setDeviceId(deviceWechatInfo.getDeviceId());
            deviceInfoMobileWeChatCacheDto.setDeviceUniqueId(deviceWechatInfo.getId());
            deviceInfoMobileWeChatCacheDto.setConfigId(deviceWechatInfo.getConfigId());
            deviceInfoMobileWeChatCacheDto.setDeviceAuths(deviceProductAuthList);
            if (deviceWechatInfo.getRecvmsgType().intValue() == DeviceTypeEnum.DT_ANDROID_WECHAT.getId()) { //手机端接收消息
                deviceInfoMobileWeChatCacheDto.setMsgHandler(1);
            } else {
                deviceInfoMobileWeChatCacheDto.setMsgHandler(0);
            }
            //更新移动端机器人redis
            redisTemplate.opsForValue().set(String.format(RedisCacheKeyEnum.DEVICE_INFO_WECHAT_MOBLE.getKey(), deviceWechatInfo.getId()), Tools.getStrEmpty(JSONObject.toJSONString(deviceInfoMobileWeChatCacheDto)));
        }
    }

    /**
     * 手机号运营商查询
     *
     * @param mobiletypeFindDto
     * @return null
     * @author jitwxs
     * @date 2023/8/17 15:47
     */
    public MobiletypeFindVo findMobiletype(MobiletypeFindDto mobiletypeFindDto) {

        //手机号类型(0：电信，1：移动， 2：联通)
        MobiletypeFindVo mobiletypeFindVo = new MobiletypeFindVo();

        if (StringUtils.isBlank(mobiletypeFindDto.getMobile())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入手机号");
        }

        if (mobiletypeFindDto.getMobile().length() != 11) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机号码有误");
        }

        String mobiletypeResult = Mobiletype.findMobiletype(mobiletypeFindDto.getMobile());
        if (StringUtils.isNotBlank(mobiletypeResult)) {
            JSONObject jsonObject = JSONObject.parseObject(mobiletypeResult);
            if (jsonObject != null) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String isp = data.getString("isp");
                    if ("电信".equals(isp)) {
                        mobiletypeFindVo.setMobiletype(0);
                    } else if ("移动".equals(isp)) {
                        mobiletypeFindVo.setMobiletype(1);
                    } else if ("联通".equals(isp)) {
                        mobiletypeFindVo.setMobiletype(2);
                    }
                }
            }
        }
        return mobiletypeFindVo;
    }

}
